I searched high and low now but I can't figure out how to get this to work:
I need to get the element whose class name contains a number that I pass with a variable.
For better understanding: This is inside a "click" event on a gallery. Whenever an img is clicked I search for the src, see which number the string contains and then want to find the matching p whose class contains the same number. So I can manipulate the matching text to the picture that is currently displayed (Since the plugin I use strips away any id or class I can only identifiy a picture by its source name).
So far it does work if I directly put the number in as a String. Like this:
var team_t = $(this).find("img").attr("src");
for(n = 1; n <=6; n++ ){
if(team_t.indexOf(n) != -1)
{
$('#text_content').find("p[class*='3']").css("background-color", "red");
}
}
But instead of "3" I want it to get the number that the variable n holds. I tried this but it did not work:
$('#text_content').find("p[class*=' + n + ']").css("background-color", "red");
Actually it didn't work with any kind of variable I tried to pass. I also saw and tried examples that use contains( ) or hasClass( ) and others.. but nothing worked for me. I'm not extremly familiar with the syntax though.
How do I have to write this so it takes the variabel as a string?
If I do alert( n ) it shows the correct number, so that's not the problem.
You were on the right track with string concatenation, you just didn't get all the way outside the string:
$('#text_content').find("p[class*='" + n + "']").css("background-color", "red");
// Change is here -----------------^- and -^
In your attempt, the + n +
was still in the outer quotes, and so was used literally in the selector (making it fail).
That said, if you have any control over the DOM structure (but it sounds like you may not), there's probably a better way. For instance, you could put a data-*
attribute on the element that gives an appropriate selector for the p
element (possibly even by id
, but that's just one option).
You might also want to end the loop once you've found the index, by putting break;
on the line after the line setting the red color.
Finally: You might want to use a class to add the red color rather than mixing your presentation into your JavaScript code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments