How to get only direct text without tags with jQuery in HTML

The best way is to .clone() your object, .remove() all of its .children(), then go back to the object using .end() and finally get the .text().

The method is described in this blog post.

$("strong")
        .clone()    //clone the element
        .children() //select all the children
        .remove()   //remove all the children
        .end()  //again go back to selected element
        .text();    //get the text of element

This is tricky, because the text is in a text node, and jQuery doesn't support text nodes, only elements. Also because different browsers treat white space in HTML code differently, so you end up with different sets of nodes in different browsers. You can't just get the nodes and rely on that the text node that you want is at the same index all the time.

You can use jQuery to locate an element, and use the DOM to get all the nodes inside it.

Example HTML:

<div id="test">
  <strong>1)</strong>
  TEXT THAT I ONLY NEED
  <p>some par</p>
  <ul>
    <li>asdf</li>
    <li>qwerty</li>
  </ul>
</div>

Use jQuery to find the div, use [0] to get the DOM element out of the jQuery object, and the childNodes property to get its children:

var nodes = $('#test')[0].childNodes;

Then you can use jQuery to loop through the nodes to find the node that is the strong element:

var index;
$.each(nodes, function(i,e){
  if (e.tagName == 'STRONG') {
    index = i;
    return false;
  }
});

Now you can use the DOM to get the text value from the next node:

var text = nodes[index + 1].nodeValue;

well, if you use jQuery, you would do

$('.selector').text();

more info and examples here

edit: I just saw you want the text that is not in any tags - well this is not directly possible (fact is, that every text inside a html document is inside some HTML tags.)

In this case I would try to change the markup (easiest way), so the desired text is within html tags. If this is not possible, you use the above mentioned text() method to get the whole text from the parent element, and after you have to subtract the pieces you dont want.

see http://jsfiddle.net/3SSAR/1/ for an example of how to subtract the strings..

just remember to use substr and not - to subtract strings in javascript