WestCoast_BC
asked on
Question about traversing a tree using jQuery
I am having trouble figuring out how I get the href of anchors in a tree. Specifically, I have something like:
<ul>
<li><a href="wwww.test1.com" class="submenu">test 1</a></li>
<li><a href="www.test2.com" class="submenu">test 2</a></li>
<li><a href="www.test3.com" class="submenu">test 3</a></li>
</ul>
<script type="text/javascript">
$('.submenu').click (function()
{
}
</script>
and if someone clicks on 'test 2' how do I get the href of the anchors that are on either side of 'test 2'?
Here is the simplest version. This differs from the above - it makes use of the fact that a jQuery event handler gets passed an HTML element. An a element's href is directly accessible on the element - you don't need to wrap the element in a jQuery object to access it.
The other difference is the addition of the preventDefault() call that stops the <a> from doing its default behaviour and navigating away from the page.
The other difference is the addition of the preventDefault() call that stops the <a> from doing its default behaviour and navigating away from the page.
<script>
$(function() {
$('.submenu').click(function(e) {
e.preventDefault();
alert(this.href);
});
});
</script>
Working sample here
Pure javascript equivalent
<script>
var els = document.querySelectorAll('.submenu');
for(var i = 0; i < els.length; i++ ) {
els[i].addEventListener('click', function(e) {
e.preventDefault();
alert(this.href);
});
}
</script>
ASKER
Thank you. What I really want are the hrefs for the two links on either side of the one that I clicked on. So, for example, if I click on 'test 2' I need to traverse the tree and get the previous link's href which in this case would be 'test 1' href and similarly I need to get the next link's href which would be 'test 3'
$(function() {
$('.submenu').click(function(e) {
e.preventDefault();
var next = this.parentNode.nextElementSibling || false;
if (next) {
alert(next.firstChild.href);
}
var prev = this.parentNode.previousElementSibling || false;
if (prev) {
alert(prev.firstChild.href);
}
});
});
ASKER
Thank you. It seems that the line:
Does this make sense and is this correct?
Thank you
next.firstChild.href
was returning undefined. When I looked at the childNodes in next it had 3 items in its list and the second one had the link that I was looking for. So I changed the line above to:next.firstChild.nextElementSibling.href
and now it seems to work.Does this make sense and is this correct?
Thank you
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window
Javascript code:
Open in new window
Or JQuery..
Open in new window
Open in new window
Every time that you click at the anchor element the function returns its href value. Now you can get it and use it as you want.