I have a title and a unorder list
<h2> here is some interesting links </h2>
<ul>
<li>link 1</li>
<li>link 2</li>
<li>link 3</li>
</ul>
what I like is to add a [+] at the end of the tag, and hide the following
-
then on click on h2, show it…. BUT i need to mak e the [+] become a [-]
- -link1
- -link2
- -link3
what is the best way to change that ?
it will look like :
closed : title [+]
open : title [-]
Assuming no changes to your current HTML, and all modifications through jQuery:
JS Fiddle demo.
Edited to explain this part of the above code:
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 thetext()of the current element. We’re comparing the result to-1becauseindexOf()returns the index of the found substring. Because the substring can be found at0(the beginning of the string),indexOf()returns-1when the string is not found. Therefore if the+is found (so the returned result will not be equal to-1) within the text of thespanelement the text is changed to[-], whereas if the+is found the text will be changed to[-].The
returnstatement simply returns the changed-text to thetext()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:JS Fiddle demo.
References:
closest().html().next().on().text().toggle().