简体   繁体   中英

Finding child element by class from parent with pure javascript cross browser

Following my code:

<div onclick="/*Here I would like to select the child element with the class 'vxf'*/">
   <div class="abc"></div>
   <div class="cir"></div>
   <!--... other elements-->
   <div class="vxf"></div>
   <!--... other elements-->
</div>
<div onclick="/*Here I would like to select the child element with the class 'vxf'*/">
   <div class="abc"></div>
   <div class="cir"></div>
   <!--... other elements-->
   <div class="vxf"></div>
   <!--... other elements-->
</div>

How to select the child element with the class "vxf" with pure javascript?

Pass this into your handler...

onclick="clickHandler(this)"

...and then for maximum browser compatibility, just look in the child nodes:

function clickHandler(element) {
    var child;
    for (child = element.firstNode; child; child = child.nextSibling) {
        if (child.className && child.className.match(/\bvxf\b/)) {
            break; // Found it
        }
    }
    // ...
}

(Or keep looping and build up an array, if you want all matching children.)

On most modern browsers , another alternative is to use querySelector (to find the first) or querySelectorAll (to get a list) of matching child elements. Sadly, this requires a bit of a trick:

function clickHandler(element) {
    var child, needsId;
    needsId = !element.id;
    if (needsId) {
        element.id = "TEMPID____" + (new Date()).getTime();
    }
    child = document.querySelector("#" + element.id + " > .vxf");
    if (needsId) {
        element.id = "";
    }
    // ...
}

We have to play the id game because we only want direct children (not descendants), and unfortunately you can't use a child combinator without something on the left of it (so element.querySelector("> .vxf"); doesn't work).

If you didn't care whether it was a direct child or a descendant, then of course it's a lot easier:

function clickHandler(element) {
    var child = element.querySelector(".vxf");
    // ...
}

Just use this.getElementsByClassName('vxf')[0] in the div 's onclick, and you have the element. See this fiddle .

in HTML5 you can use document.querySelector('.vxf')

As pointed out in other answers you can also use document.getElementsByClassName('vxf') for this specific requirement but the document.querySelector() and document.querySelectorAll() methods allow you to provide more complex selectors and therefore give you more power, so worth looking at for future.

See here for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM