Your attempt does not work because the click event handler is attached to the whole span
element, which comprises the icon and the link.
To make it work, you have to make 2 small modifications to the javascript code:
- attach the click handler to the
i
element (which holds the icon) using this selector:.tree li.parent_li > span > i
- Adapt the references to
$(this)
to refer to the parentspan
So the whole javascript code would become:
$(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span > i').on('click', function (e) {
var $this = $(this);
var $span = $this.parent();
var children = $span.parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$span.attr('title', 'Expand this branch');
$this.addClass('icon-plus-sign').removeClass('icon-minus-sign');
} else {
children.show('fast');
$span.attr('title', 'Collapse this branch')
$this.addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
});
$('.icon-plus-sign').parent().next().next().children('li').hide();
3
solved How do I change the anchor link in JQuery?