Reputation: 85
I'm having some problems understanding the stracture of JQuery elements and how to move through the DOM tree.
My aim is to highlight (background color) the clicked link (a). if the "li a" is inside ul which is not the main "menu" ul (meanning sub-menu link) then i want to highlight both the sub menu link and the top menu link.
My HTML code is:
<div id="site">
<div id="koteret">
<div id="top_menu">
<ul id="menu">
<li><a href="welcome.html" id="wel" title="HomePge" >home</a></li>
<li><a href="welcome.html" id="d" title="c">read</a>
<ul class="par">
<li><a href="welcome.html" id="b" title="title" >test</a></li>
<li><a href="Register_client.aspx" id="c" title="add">addRead</a></li>
</ul>
</li>
<li><a href="books.aspx" title="Books" >Books</a>
<ul class="par">
<li><a href="books.aspx" title="Manage">Search</a></li>
<li><a href="Register_book.aspx" title="addbook">Register</a></li>
</ul>
</li>
<li><a href="contact.html" id="a" title="Contact" >CoNTACT</a></li>
</ul>
</div>
</div>
<div id="test">
<iframe id="con" src="welcome.html">ffffffffffffffffffffffffffffffsdfdsfsdfwefwfwfw
fwfwefwe<br />fwefwefw</iframe>
<div id="side_bar">fsfdsfsdf</div>
</div>
<div id="footer">footer</div>
</div>
</body>
As for the JQuery i tried this:
$(this).closest("ul").find("a").attr("id"));
and a few other versions with parents but i get "undefined" or empty strings when i check with alerts. Can you help me understand where is my mistake? I'm sure it's something very simple i just can't find it. Thanks
Upvotes: 2
Views: 250
Reputation: 1547
To highlight the submenu link and its top most parent link use the following code:
$(this).css("background-color","red");
$(this).parents("li").last().find("a:first").css("background-color","red");
The first line highlights the link.
The second line will look for the top-most 'li'
then select its immediate 'a'
tag and highlight it
UPDATE:
To remove the highlight of the previous click use a CSS class:
.highlight {
background-color: red;
}
Then use the following code:
$("#menu").find(".highlight").removeClass('highlight');
$(this).addClass('highlight');
$(this).parents("li").last().find("a:first").addClass('highlight');
Upvotes: 1