Reputation: 1629
How can I output the text to the parent <div>
's <span>
? What am i doing wrong?
If there are any better solutions than working with spans and .parent()
, please let me know.
HTML:
<div>
<span></span> <!--the span where i want to output "troll" and "dwarf"-->
<a href="#" class="heroes" alt="troll">Icon</a>
<a href="#" class="heroes" alt="dwarf">Icon</a>
</div>
<div>
<span></span <!--the span where i want to output "witch"-->
><a href="#" class="heroes" alt="witch">Icon</a>
</div>
<div>
<span></span> <!--etc...-->
<a href="#" class="heroes" alt="barbarian">Icon</a>
</div>
<div>
<span></span>
<a href="#" class="heroes" alt="necromancer">Icon</a>
</div>
JS:
$('.heroes').hover(function() {
var hero = $(this).attr('alt');
$(this).parent('span').text(hero);
}, function() {
$(this).parent('span').text("");
});
Thanks
Upvotes: 0
Views: 9659
Reputation: 150253
$(this).siblings('span').text(hero);
The span is a sibling of the anchor, not it's parent.
Indent your HTML, and you see it very easily:
<div> <!--The parent of the span and anchors!-->
<span></span> <!--Sibling of the anchors!-->
<a href="#" class="heroes" alt="troll">Icon</a>
<a href="#" class="heroes" alt="dwarf">Icon</a>
</div>
Note: alt
isn't a valid HTML attribute for an anchor.
Upvotes: 5
Reputation: 382696
Use:
$(this).closest('div').find('span').text(hero);
<span>
is sibling not parent of your links, you can find it based on actual <div>
parent.
Upvotes: 1