JQuery: find element whose class contains variable value

I've searched high and low now, but I can't figure out how to get this to work:

I need to get an element whose class name contains a number that I am passing with a variable.

For a better understanding: this is inside the "click" event in the gallery. Whenever img is clicked, I search for src, look at which number contains the string, and then want to find the corresponding p, whose class contains the same number. So I can manipulate the matching text from the image that is currently displayed (since the plugin I'm using removes any id or class, I can only identify the image by its name).

So far this works if I directly put a number 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 has. I tried this but it didn't work:

$('#text_content').find("p[class*=' + n + ']").css("background-color", "red");

      

It didn't actually work with any variable that I was trying to pass. I've also seen and tried examples that use contains () or hasClass () and others .. but nothing worked for me. However, I am not familiar with the syntax.

How do I write it so that it takes the variable as a string?

If I alert (n) it shows the correct number, so no problem.

+3


source to share


1 answer


You were on the right track with string concatenation, you just didn't get to the line:

$('#text_content').find("p[class*='" + n + "']").css("background-color", "red");
// Change is here -----------------^- and -^

      

In your attempt + n +

, it was still in outer quotes and therefore used literally in a selector (which fails).


That said, if you have any control over the DOM structure (but doesn't seem to be the case), there might be a better way. For example, you can put an attribute data-*

on an element that gives the appropriate selector for the element p

(maybe even with id

, but that's only one option).




You can also end the loop after finding the index by placing it break;

in the line after the line that specifies red.


Finally: you can use the class to add red rather than mixing the presentation into your JavaScript code.

+5


source







All Articles