I\'ve got an HTML:
1)TEXT THAT I ONLY NEEDsome par
..
I need only
This code works for me:
var el = $("<div/>");
el.html(text).children().remove();
return el.text();
Yet another approach With vanila/pure
JavaScript
const el = document.getElementById('element');
const elNodes = el.childNodes;
let plainText = "";
for(i=0;i<elNodes.length;i++){
if(elNodes[i].nodeName == '#text'){
plainText+=elNodes[i].textContent;
}
}
console.log(plainText); // prints TEXT THAT I ONLY NEED
<!-- html -->
<div id='element'>
<strong>1)</strong>TEXT THAT I ONLY NEED
<p>some par</p>
<ul>..</ul>
</div>
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
var name = $($(YourElementOuterHTML)).children().remove().end().text();
example:-
var name = $($(li).find("a").get(0).outerHTML).children().remove().end().text();
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
Your markup isn't the greatest for this. If you wrapped the text you want with a span such as:
<span class="gettext">TEXT THAT I NEED</span>
You could use $('.gettext').text();
in jQuery.