I’m having a problem where my drop-down list is toggling the entire set of li elements. I was just wondering how I could change my jQuery to target the first child ul of the parent, in this case the span element I clicked on.
Is there a simple way to fix this problem? I attached a JSFiddle below, also not entirely sure why list has a giant left margin but that seems trivial.
The HTML
<dl id="sample" class="dropdown">
<dt><a href="#"><span>COUNTRIES</span></a></dt>
<dd>
<ul>
<li><a href="#">Brazil<img class="flag" src="br.png" alt="" /><span class="value">BR</span></a></li>
<li><a href="#">France<img class="flag" src="fr.png" alt="" /><span class="value">FR</span></a></li>
<li><a href="#">Germany<img class="flag" src="de.png" alt="" /><span class="value">DE</span></a></li>
<li><a href="#">India<img class="flag" src="in.png" alt="" /><span class="value">IN</span></a></li>
</ul>
</dd>
<dt><a href="#"><span>PLANETS</span></a></dt>
<dd>
<ul>
<li><a href="#">EARTH<img class="flag" src="br.png" alt="" /><span class="value">BR</span></a></li>
<li><a href="#">SATURN<img class="flag" src="fr.png" alt="" /><span class="value">FR</span></a></li>
<li><a href="#">MARS<img class="flag" src="de.png" alt="" /><span class="value">MR</span></a></li>
<li><a href="#">PLUTO(JK)<img class="flag" src="in.png" alt="" /><span class="value">PL</span></a></li>
</ul>
</dd>
</dl>
<span id="result"></span>
jQuery
$(document).ready(function() {
$(".dropdown img.flag").addClass("flagvisibility");
$(".dropdown dt a").click(function() {
$(".dropdown dd ul").toggle();
});
$(".dropdown dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
$("#result").html("Selected value is: " + getSelectedValue("sample"));
});
function getSelectedValue(id) {
return $("#" + id).find("dt a span.value").html();
}
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
$(".dropdown dd ul").hide();
});
$("#flagSwitcher").click(function() {
$(".dropdown img.flag").toggleClass("flagvisibility");
});
});
In your
clickhandlers you can’t just use class specifiers – that’s why your actions are affecting every matching element.You’ll need to traverse the DOM tree (i.e.
.parent(),.child(), etc) to find the related elements that you want to modify.For example in this handler:
your presumably wish to show the
dd > ulelement that follows the<dt>that contains the clicked<a>:although that said (per comments), if your HTML markup stays as it is you can simplify it as follows, since there’s only one
<ul>and the<dd>always follows the<dt>: