开发者

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

开发者 https://www.devze.com 2023-03-28 16:46 出处:网络
How to get the text from a p开发者_StackOverflowarent DIV when it has child elements with text using jQuery?

How to get the text from a p开发者_StackOverflowarent 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.


Try with:

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


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.


<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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消