Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector with nested nth-child in Chrome doesn't appear to work

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?

like image 304
zacharyc Avatar asked Jun 14 '11 14:06

zacharyc


People also ask

How do you use the nth child in querySelector?

To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document. querySelector('#parent :nth-child(1)') . The nth-child pseudo-class returns the element that matches the specified position.

How do you get children of querySelector?

Use the :scope pseudo-class to get the direct children of an element using querySelectorAll, e.g. parent. querySelectorAll(':scope > div') . When used with the querySelectorAll method, :scope matches the element on which the method was called.

What's the difference between the nth of type () and Nth child () selectors?

The nth-of-type is very similar to the nth-child pseudo-class. The main difference is that it specifically considers the type of the element getting selected before checking any other logic. Let's use our example from above but apply nth-of-type instead.

How do I access my nth child?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.


1 Answers

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.

like image 148
DanielB Avatar answered Sep 21 '22 13:09

DanielB