How to change CSS where id = array (index)?

I will just write a little code that should change CSS X ids.

I have 3 identifiers in HTML objects (each element has 1 class) =

element 1 id = "p1" class = "test1"
element 2 id = "p2" class = "test1"
element 3 id = "p3" class = "test1"

i create two arrays:

 var statArray = ["p1","p3"];
 var array = ["p1","p3"];

than I check if Array 1 = Array 2

for (var ix = 0; ix < array.length; ix++) {
if (array[ix] === statArray[ix])

Now I will change the css (background-color) identifiers.

How can I change identifiers, where id = array [ix]?

my attempt:

$(".test1").attr(array[ix]).css("background-color","#ff0000");
+4
source share
3 answers

Just use this

for (var ix = 0; ix < array.length; ix++) {
    if (array[ix] === statArray[ix]){
        $(".test1#"+array[ix]).css("background-color","#F00");
    }
}
+1

id # :

$("#"+array[ix]).css("background-color","#ff0000");

$("[id="+array[ix]+"]").css("background-color","#ff0000");
+3

I would rather not require the DOM in a loop at all. You can cache the result in a variable:

var $test = $(".test1");

for (var ix = 0; ix < array.length; ix++) {
    if (array[ix] === statArray[ix]) {
        $test.filter('#' + array[ix]).css("background-color", "#ff0000");
    }
}
+1
source

Source: https://habr.com/ru/post/1542048/


All Articles