Reputation: 5
My goal is that when the user clicks on the <div class="title">
, the text within the <span>
inside the containing <h3>
will change and when the click again it will go back to its previous value.
<div class="title">
<h3>Text The Doesn't Change <span>Text That Changes</span></h3>
</div>
However when I click on the div, the text changes once and then stops no matter how many times I click.
If I remove the text before the span from the code:
<div class="title">
<h3><span>Text That Changes</span></h3>
</div>
Then it works fine however I need that text to be present for my specific application.
Here is my jQuery code:
$('div.title').click(function(){
$(this).children('h3').children('span').text($(this).text() == '-' ? '+' : '-');;
});
Here is a link to the page to see what I am: Demo
Upvotes: 0
Views: 1044
Reputation: 23537
In this condition you are accessing the wrong element (div.title
):
$(this).text() == '-' ? '+' : '-'
This should be:
$('h3 > span', this).text() === '-' ? '+' : '-'
Everything all together can be reduced to:
$('div.title').click(function(){
var $span = $('h3 > span', this);
$span.text($span.text() === '-' ? '+' : '-');
});
Upvotes: 0
Reputation: 92963
Replace .children(...)
with .find(...)
-- in your first code block, the <span>
is actually a direct child of the text node, not of the <h3>
. Using .find
will drill down as far as needed to locate the <span>
.
UPDATE
Your use of this
inside the .text()
method isn't pointing to what you think it is. Try using a callback function instead:
$('div.title').click(function(){
$(this).find('span').text(function(i,t) {
return (t=='-') ? '+' : '-';
});
});
Upvotes: 2