harshavmb harshavmb - 5 months ago 17
Javascript Question

how to change background color of multiple td elements using jquery

I'm unable to change the background color of multiple td elements in a table using jquery.

HTML code :

<td id="trueValue">/com/website/seo/</td>

<td id="trueValue">/com/website/seo/</td>

<td id="falseValue">/com/website/seo/</td>

<td id="falseValue">/com/website/seo/</td>


Jquery code :

$("td").each(function() {
var i = $(this).attr("id");
if (i == "trueValue") {
$(i).css("background-color", "green");
}
});


The above jquery is doing nothing. Can someone correct my code please?

Many Thanks in advance.

Answer

You cannot have multiple elements with the same id. Your HTML in this example would be invalid. If you want to group elements, use classes. Then you can just select the elements by class and apply the styling to them, like this:

$('.truevalue').addClass('foo');
.foo {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="truevalue">/com/website/seo/</td>
    <td class="truevalue">/com/website/seo/</td>
    <td class="falsevalue">/com/website/seo/</td>
    <td class="falsevalue">/com/website/seo/</td>
  </tr>
</table>

Comments