Alexa Green
Alexa Green

Reputation: 1183

How to traverse DOM and console.log each unique paragraph's text

I would like to be able to console.log the caption text from each paragraph on hover. The problem I am having is it is not outputting the correct caption text.

jQuery('.videogall-thumb').each(function () {
    jQuery(this).hover(function () {
        var name = jQuery('videogall-caption').html();
        console.log(name);
    });
});

<div class="videogall-thumb">
    <p class="videogall-caption">Jon</p>
</div>
<div class="videogall-thumb">
    <p class="videogall-caption">Bob</p>
</div>
<div class="videogall-thumb">
    <p class="videogall-caption">Mark</p>
</div>

Upvotes: 0

Views: 331

Answers (2)

codetantra
codetantra

Reputation: 258

jQuery('.videogall-thumb').each(function() { 
    jQuery(this).hover(function(){ 
        var name = $('> .videogall-caption', this).html(); 
        console.log(name); 
    }); 
}); 

Upvotes: 0

James Montagne
James Montagne

Reputation: 78650

jQuery('.videogall-thumb').mouseenter(function(){
    var name = jQuery(this).find('.videogall-caption').text();
    console.log(name);
});

The changes I made:

  • Missing . in your selector for videogall-caption.
  • Use mouseenter instead of hover. Hover will fire on enter and leave.
  • Don't need the each at all, just call mouseenter on the collection.
  • Use find to find the appropriate element instead of grabbing all of them (children could be used instead if needed).
  • Use text to just get the text in case there are html elements within (maybe not a concern for you).

Upvotes: 2

Related Questions