29

I've been looking at using nth-child within an nth-child selector to find an element. This appears to work in Firefox, but does not seem to be working on chrome. Here's my test file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>untitled</title>
    <!--[if IE]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <script type="text/javascript" charset="utf-8">
        myFunc = function() {
            if(document.querySelector('#wonderful DIV:nth-child(2) DIV:nth-child(2)')) {
                alert("found the element");
            } else {
                alert("element not found");
            }
        };
    </script>
</head>
<body onLoad="myFunc()">

    <div id="wonderful">
       <div>
       </div>
       <div >
           <div>
           </div>
           <div class="blue">
               find me!
           </div>
       </div>
    </div>

</body>
</html>

Has anyone else seen this issue? Have a solution to get around this?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
zacharyc
  • 381
  • 1
  • 3
  • 6

2 Answers2

29

This worked for me in chrome, but it does not work in FF then.

document.querySelector('#wonderful div:nth-child(2):nth-child(2)')

The following snipped works in both browsers, but I assume you know that already

document.querySelector('#wonderful div:nth-child(2) div.blue')

So it looks like an implementation failure in chrome for me.

DanielB
  • 19,910
  • 2
  • 44
  • 50
  • yeah, very interesting. Hadn't tried the first, but the second I knew. Would be nice to have a cross browser way of doing this without using XPath. – zacharyc Jun 14 '11 at 16:11
  • 2
    Your first snippet doesn't make sense. Well, it does, but `:nth-child(2):nth-child(2)` is the same as `:nth-child(2)`... – BoltClock Jun 14 '11 at 23:03
  • 2
    @BoltClock You are right, it makes no sense but it works. This is why I assumed that's an implementation bug in chrome. – DanielB Jun 15 '11 at 07:26
  • 1
    @DanielB I think it may be a bug, as I have been trying :not():not() and it seems to only respect the first one.. but the css selects the correct element, but javascript does not. Not checked other browsers yet. – WORMSS Jul 30 '14 at 14:41
10

Found this (very old) question while hunting down a red herring. This answer is to note: today, Chrome v73 works just fine. Snippet here proves it:

const sel = '#wonderful div:nth-child(2) div:nth-child(2)';
console.log(document.querySelector(sel))
 <div id="wonderful">
    <div></div>
    <div>
       <div></div>
       <div class="blue">find me!</div>
    </div>
 </div>
Phrogz
  • 296,393
  • 112
  • 651
  • 745