user961627
user961627

Reputation: 12747

jQuery display text nested in paragraphs inside a div

I have HTML that looks something like this:

<div class='textbox' data-title='Sometitle'>
<div class='textareaedit'>
     <p><strong>Test sample text</strong></p>
</div>
</div>

I'm sometimes going to have a few different <p> tags inside the textareaedit divs, and sometimes strong tags around the text inside the <p> (as in this example), and sometimes a span tag, and sometimes it's going to be without further tags inside the <p>.

I want to iterate through each textbox on my page, grab its title and also the text nested inside <p> tags in textareaedit. I'm giving the output via console for testing. This is my jQuery code, but I get no output for the second console.log() line:

$('.textbox').each(function() {
    $this = $(this);
    console.log($this.attr('data-title')+ ":\n");
    $this.children('textareadit').children('p').each(function(){
        console.log($(this).html()); // not giving any output, it's blank
    });
});

I tried $(this).text() as well, but no difference. You may think this example has the sample text inside <strong> tags within the <p>, but I've also tried the same example without the strong, where the text was the direct child of <p>, but it didn't make a difference. How can I capture the text?

Upvotes: 0

Views: 1234

Answers (5)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

You are missing a . in your selector, and there is a typo in your textareadit. The correct one should be -

$this.children('.textareaedit').children('p').each(function(){
    console.log($(this).html()); // now it prints
});

You are passing class selector as argument to the first children call, so you should precede it with a ., as this is how class selectors works.

JSFiddle.

Upvotes: 1

Sanjeev
Sanjeev

Reputation: 173

Class name is also misspelled

.children('textareadit') should be .children('.textareaedit')

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

The class selector passed to the children() function is missing a . prior to the class name. There is also a spelling error in the name of the class, textareadit should be textareaedit.

$this.children('.textareaedit').children('p').each(function(){
    console.log($(this).html()); // not giving any output, it's blank
});

Example: http://jsfiddle.net/aWRaS/

Upvotes: 2

buffcoredave
buffcoredave

Reputation: 179

.children('textareadit')

should read:

.children('.textareadit')

As you're selecting a class

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38608

You can use find() method to locate it. Try something like this:

$this.find('.textareadit > p').each(function(){
    console.log($(this).html());
});

Upvotes: 1

Related Questions