Skip to content Skip to sidebar Skip to footer

Iterate Each Div Attribute Using Jquery?

I'm trying to get the rgb and index value of each div. In the console I get everything correctly (index and B background color for each div). Trying to add each value to a p in eve

Solution 1:

Change the following...

$("div p").text(index+x);

To...

$(this).find("p").text(index+x);

As currently you are finding ALL <div> elements again, and populating the <p> in each one... that is why you're seeing the final value across all

$('div').each(function(index) {
  var x = $(this).css('background-color');
  $(this).find("p").text(index+x);
  console.log(index+x);
});
.red {
    background-color:red; 
}.orange {
    background-color:orange; 
}
.yellow {
    background-color:yellow; 
}
.purple {
    background-color:purple; 
}
.blue {
    background-color:blue; 
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="red"><p></p></div><divclass="orange"><p></p></div><divclass="yellow"><p></p></div><divclass="purple"><p></p></div><divclass="blue"><p></p></div>

Solution 2:

Basically you had the right function, but need to use .eq(index) to actually effect that specific index within the foreach function. This is similar to accessing indexes in arrays, such as randomArray(0) => 1.

$('div').each(function(index) {
  var x = $(this).css('background-color');
  $("div p").eq(index).text(index+x);
  console.log(index+x);
});
.red {
    background-color:red; 
}

.cyan {
  background-color:cyan;
}

.green {
  background-color:green;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="red"><p></p></div><divclass="cyan"><p></p></div><divclass="green"><p></p></div>

Post a Comment for "Iterate Each Div Attribute Using Jquery?"