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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With