rix
rix

Reputation: 10632

Jquery, get text value from divs on the same level using each()

Given the div structure below, I'm trying to get the text in each div.class content.

I've been using next() which only works for the first 2 elements and is a bit unwieldy. Is there a way I can get the content values using selectors (would be more elegant)?

Because there are many holder divs on the page I need to use the selectors relative to each holder div.

Thanks,

$(".holder").each(function() {
var image = $(this).next().text();  //get value   
var title = $(this).next().next().text(); //gets value
} 

<div class="holder">
    <div class="field-image">
        <div class="content">content</div>  
    </div>
    <div class="field-title">
        <div class="content">content</div>  
    </div>
    <div class="field-location">
         <div class="content">content</div>  
    </div> 
   <div class="field-sector">
         <div class="content">content</div> 
   </div>
</div>

Upvotes: 0

Views: 966

Answers (2)

JohnJohnGa
JohnJohnGa

Reputation: 15685

$(".holder").each(function() {
  $(this).find('div[class*=field]').each(function() {
    var $image = $(this);
    var $content = $image.find('div.content');
    var text = $content.text();
  });
});

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816422

It seems you just need to get the text content of each child (or of the .content element of each child):

$('.holder').each(function() {
    var texts = {};
    $(this).children().each(function() {
        // Assuming each child has only one class
        texts[this.className.replace(/^field-/, '')] = 
            $(this).find('.content').text();
    });

    // now do something with e.g. texts.image, texts.title, etc.
});

Upvotes: 1

Related Questions