Assuming no changes to your current HTML, and all modifications through jQuery:
$('h2').html(
function(i,h) {
return h + '<span>[+]</span>';
}).on('click', 'span', function(){
var that = $(this);
that.closest('h2').next('ul').toggle();
that.text(
function(){
return that.text().indexOf('+') !== -1 ? '[-]' : '[+]';
});
});
JS Fiddle demo.
Edited to explain this part of the above code:
return that.text().indexOf('+') !== -1 ? '[-]' : '[+]';
This is a ternary operator, it evaluates a condition (return that.text().indexOf('+') !== -1
) for being true, or false. Following the ?
is the 'if-true' response, and following the :
is the 'if-false' response.
So, the condition assesses whether or not the +
character is found within the string returned from the text()
of the current element. We're comparing the result to -1
because indexOf()
returns the index of the found substring. Because the substring can be found at 0
(the beginning of the string), indexOf()
returns -1
when the string is not found. Therefore if the +
is found (so the returned result will not be equal to -1
) within the text of the span
element the text is changed to [-]
, whereas if the +
is found the text will be changed to [-]
.
The return
statement simply returns the changed-text to the text()
method.
Updated to amend the text()
method's function, and take advantage of the fact that the text of the element is available as the second parameter in the function:
$('h2').html(
function(i,h) {
return h + '<span>[+]</span>';
}).on('click', 'span', function(){
var that = $(this);
that.closest('h2').next('ul').toggle();
that.text(
function(i,t){
return t.indexOf('+') !== -1 ? '[-]' : '[+]';
});
});
JS Fiddle demo.
References: