khalil _diouri khalil _diouri - 4 months ago 7
jQuery Question

get text content of first HTML tag

I need to get just text of html tag Div where

(id = 'div12Item')
that is
(new content )

below is my html code

<div name="div12Item" id="div12Item">

new content
<ul id="sortable" >

<li ></span>Item 1</li>
<li ></span>Item 2</li>
<li ></span>Item 3</li>

</ul>
</div>


when I execute this javascript code
alert(document.getElementById('div12Item').textContent);

I get new content Item 1 Item2 Item3

but me I need just get text in div even if in HTML tag Div there is other HTML tags like my example

Answer

You can filter out element that have nodetype equal to textnode along with .text() to get text of it:

var text = $("#div12Item").contents().filter(function() {
  return this.nodeType == Node.TEXT_NODE;
}).text();

var text = $("#div12Item").contents().filter(function() {
  return this.nodeType == Node.TEXT_NODE;
}).text();
alert(text.trim());
   <div name="div12Item" id="div12Item">

            new content            
          <ul id="sortable" > 

            <li ></span>Item 1</li> 
            <li ></span>Item 2</li> 
            <li ></span>Item 3</li> 

        </ul> 
       </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>