happy_story
happy_story

Reputation: 1163

Why is :nth-child() not working in JavaScript?

$("#oddcolor")[0].onclick = function() { 
  $(".coltest:nth-child(odd)")[0].style.backgroundColor = "red";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<button id="oddcolor">Click me</button>

It seems that it applies to only the first odd number element, and then it stops. Why is it not applying to all the odd elements?

I've tried using querySelectorAll, and it's not working either. I've tried creating a parent container, and then targeting the child elements via the parent, like this .parent div:nth-child(odd), but again, only applies to the first odd number. I've tried without jquery, same result, although, without jquery, if I have to use getElementsByClassName, I don't know how to add the nth-child(odd), because document.getElementsByClassName("coltest:nth-child(odd)")[0].style.backgroundColor = "red"; this creates an error, and without the [0], it also creates an error.

It works if I use CSS instead, but why is it not working in Javascript?

Upvotes: 0

Views: 188

Answers (1)

Barmar
Barmar

Reputation: 782775

Using [0] only operates on the first element of the jQuery collection. If you want to process all of them, you need a loop.

But since you're using jQuery, use its .css() method, which will automatically process every element in the collection.

$("#oddcolor").click(function() { 
  $(".coltest:nth-child(odd)").css('backgroundColor', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<div class="coltest">test</div>
<button id="oddcolor">Click me</button>

Upvotes: 3

Related Questions