Alessandra Refinale Alessandra Refinale - 2 months ago 13
HTML Question

DOM traversal from a span element inside an anchor to list

I can't figure how to travers the DOM, starting from

<span class = "open-menu-link">
, I want to reach
<ul class="sub-menu">
.

The script

<script> $('.open-menu-link').click(function(e){
alert(e.currentTarget);
});
</script>


return a Object HTMLSpanElement, but if I code
e.currentTarget.parentNode;
it returns
http://localhost/mysite/home.php
. Doing
e.currentTarget.children;
I get Object HTMLCollection, but if I try
e.currentTarget.children[1]
I get undefined... so how can I reach
<ul class="sub-menu">
?
The snippet is the follow:

<ul class="menu">
<li><a href="#work">Work</a></li>
<li class="menu-item-has-children"><a href="#about">Haschildren <span class = "open-menu-link">+</span></a>
<ul class="sub-menu">
<li><a href="#link1">Child 1</a></li>
<li><a href="#link2">Child 2</a></li>
<li><a href="#link3">Child 3</a></li>
</ul>
</li>
<li><a href="#careers">Careers</a></li>
<li><a href="#contact">Contact</a></li>
</ul>

Answer

$(function() {
$('.open-menu-link').click(function(e){ 
	console.log(e.target.parentNode.nextElementSibling);
	console.log(e.target.parentNode.parentNode.children[1]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li><a href="#work">Work</a></li>
    <li class="menu-item-has-children">
        <a href="#about">Haschildren <span class="open-menu-link">+</span></a>
        <ul class="sub-menu">
            <li><a href="#link1">Child 1</a></li>
            <li><a href="#link2">Child 2</a></li>
            <li><a href="#link3">Child 3</a></li>
        </ul>
    </li>
    <li><a href="#careers">Careers</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>

There are couple of options:

$('.open-menu-link').click(function(e){ 
    console.log(e.target.parentNode.nextElementSibling);
    console.log(e.target.parentNode.parentNode.children[1]);
});
Comments