Reputation: 1877
What I'm trying to do is add a [+]
or [-]
sign to an expandable heading so that once the user clicks on the heading, its content part will be shown and its sign part will change from +
to -
and vice versa. Since there are multiple headings, I used jQuery's next()
. So far the .content
toggling works well, but for some reason the sign is not changing.
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
jQuery(".heading").click(function()
{
jQuery(this).next(".content").toggle();
if (jQuery(this).next(".sign").text()=="[+]")
{jQuery(this).next(".sign").text("[-]");}
else
{jQuery(this).next(".sign").text("[+]");}
});
});
</script>
for (int i = 0; i < nodes.getLength(); i++)
{
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("Title");
Element ttl = (Element) title.item(0);
String linkTitle = getCharacterDataFromElement(ttl);
htmlReturn += "<a href='#' class='heading'><h4>" + linkTitle + " <span class='sign'>[+]</span></h4></a>";
htmlReturn += "<div class='content'>";
...
}
Upvotes: 0
Views: 1026
Reputation: 55339
Because the sign is a descendant element of the heading, not a sibling, use find
instead of next
:
var sign = jQuery(this).find(".sign");
sign.text(sign.text() === "[+]" ? "[−]" : "[+]");
// Note: A minus sign (−) has the same width as a plus sign (+),
// whereas a hyphen (-) is typically narrower.
Upvotes: 3
Reputation: 94101
Well, next()
only gets the immediate sibling. Try using closest()
instead.
Upvotes: 0
Reputation: 13065
if (jQuery(".sign").text()=="[+]")
{jQuery(".sign").text("[-]");}
else
{jQuery(".sign").text("[+]");}
Upvotes: 1