manraj82
manraj82

Reputation: 6295

How to get text only from the DIV when it has child elements with text using jQuery?

How to get the text from a parent DIV when it has child elements with text using jQuery?

<div id='div_1'>
  I am a DIV
  <span>
    I am a SPAN
  </span> 
</div>

If I was to use $('#div_1').text(),it will give me 'I am a DIV I am a SPAN'.How do I get just the text 'I am a DIV from' div_1? Any help much appreciated,thank you.

Upvotes: 2

Views: 3427

Answers (4)

genesis
genesis

Reputation: 50966

<div id='div_1'> 
  I am a DIV 
  <span> 
    I am a SPAN 
  </span>  
</div> 
<script> 
$(function(){ 
    $("#div_1").contents().filter('*').remove(); 
}); 
</script>

http://sandbox.phpcode.eu/g/c4fb9.php

Upvotes: 1

hayesgm
hayesgm

Reputation: 9086

You can access the text-node that you are looking for directly. In your case, use the following:

 $('#div_1')[0].childNodes[0].nodeValue

Every node has a list of child nodes, which may be other HTML elements, or text-nodes. Thus, we are getting the first child (in your case a text node) and returning the nodeValue which will be the text itself. Here's an example.

Upvotes: 1

David Aleu
David Aleu

Reputation: 3942

Try with:

$('#div_1').clone().children().remove().end().text();

Upvotes: 3

Bojangles
Bojangles

Reputation: 101473

You can use .remove() to get rid of the HTML elements inside the div. Here's a JSFiddle.

And the code to go with it:

HTML

<div id='div_1'>
  I am a DIV
  <span>
    I am a SPAN
  </span> 
</div>

<div id="output"></div>

JavaScript

$(document).ready(function() {
    var div = $("div#div_1").clone();
    
    div.find("*").remove();
    
    $("div#output").text(div.text());
});

I've made it a little more complex than it needs to be (using .clone()) so the div's original content is preserved. If you just want to get the text and don't care about the original content, you can leave the .clone() out.

Upvotes: 0

Related Questions