Duk
Duk

Reputation: 135

Selectively getting text from <div>

<div class="myDiv">
    <p>I need get<strong>this</strong>
        <a title="And this" href="#">but not this</a>
    </p>
    <p>And also<strong>This</strong>
        <a title="And this" href="#">but not this</a>
    </p>
</div>

How do I grab everything in p tag except for the text in nested a tag. And also I need to get values for "title" attirbute for tag a?

Upvotes: 1

Views: 92

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Using http://api.jquery.com/replaceWith/

  • Creates a clone
  • Replaces the a tags with their title attributes
  • Calls text() on the cloned node

http://jsfiddle.net/mendesjuan/cBejv/2/

var clone = $('.myDiv p').clone();
clone.find('a').replaceWith(function() {
   return this.getAttribute('title');
})
console.log(clone.text());

Outputs

I need get this

 And this And also This

 And this 

Upvotes: 2

j08691
j08691

Reputation: 207861

How about this:

$('.myDiv a').text('');
$('.myDiv p').each(function() {
    console.log($(this).text()+$('a',this).attr('title'));
});

jsFiddle example.

Upvotes: 1

Bryan Downing
Bryan Downing

Reputation: 15472

Something like this would work. There may be a much better way to do this, but this was the first thing to come to mind.

var $clone = $('.myDiv').clone();

$clone.find('a').remove();

$('#output').append($clone.text());​

Make sure you add an element with id="output" to see the results.

Upvotes: 1

Related Questions