0

How would I access the 2nd div's inner divs text?

<script>
$(document).ready(function() {
    for(var i = 0; i <= $('.content').length - 1; i++) {
        $('.content').eq(i).click(function(e) {
                     $(this).hide();
            })
        }          
});
</script>

<div class='content'>
   <div class='text'>foo</div>
</div>

<div class='content'>
   <div class='text'>bar</div>
</div>

<div class='content'>
   <div class='text'>foobar</div>
</div>
2
  • Post some HTML, then we can see the structure of the page. Commented Nov 2, 2011 at 18:59
  • stackoverflow.com/editing-help Commented Nov 2, 2011 at 18:59

4 Answers 4

1
$("div.content:eq(1) .text").text()
Sign up to request clarification or add additional context in comments.

Comments

1

Try using the :eq() selector

$('div.content:eq(1) div.text').text(); //will return the actual text of the inner div

$('div.content:eq(1) div.text');  //will return the inner div with class text.

Comments

1

I'm not sure if the posted jquery code is relevant to the question, but to access the text "bar", the 2nd div's inner div's text, you can do the following:

$(".content").eq(1).find(".text").text();

This says, get elements with the class of content, grab the 2nd one (eq is 0 based). Then find within it, elements with the class text and get the text within the first one.

Comments

1

Example -

$('div.content div.text').eq(1).html()

Demo @ http://jsfiddle.net/HBZFQ/1/

1 Comment

You should remember that just class selection can prove to have poor performance on large HTML pages. You should consider using `$('div.content div.text') instead of just the class selector, as it is more efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.