Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 680
user2799274 Avatar asked Dec 01 '22 20:12

user2799274


2 Answers

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");
    // ...
}
like image 72
T.J. Crowder Avatar answered Dec 03 '22 08:12

T.J. Crowder


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

like image 44
PurkkaKoodari Avatar answered Dec 03 '22 10:12

PurkkaKoodari