Prashant
Prashant

Reputation: 937

How to extract text directly under an HTML tag using Javascript

I need to extract the text that is directly under an HTML tag. For example, if my HTML looks like:

<span>This is Outside Text
      <span>This is Inside Text</span>
</span>

then I need a way to extract ONLY "This is Outside Text" and NOT "This is Inside Text". I have tried "innerHTML", innerText", "textContent" and also tried to use RegEx (although I am not very good at it). But I am unable to find a solution. Any help would be much appreciated.

Please note that due to some technical constraints, I need to use "plain" Javascript ONLY and NOT jQuery (which I know is nothing but Javascript, but I am forbidden from using it for this solution)

Upvotes: 0

Views: 1126

Answers (3)

Christophe
Christophe

Reputation: 28174

You are looking for the text children (childNodes of type 3):

var children=document.getElementById("mySpan").childNodes,
    count=children.length,
    text="";

for (var i=0;i<count;i++) {
    if (children[i].nodeType==3) {
        text+=children[i].nodeValue;
    }
}

Live demo: http://jsfiddle.net/aDgPj/

Upvotes: 0

btevfik
btevfik

Reputation: 3431

you can do it like this. it also works if you have more text after the second span.

 <span id="span1">This is Outside Text
  <span id="span2">This is Inside Text</span>
 </span>


var element = document.getElementById("span1");
var element2 =  document.getElementById("span2");

var text = element.textContent.replace(element2.textContent, "");

alert(text);

http://jsfiddle.net/btevfik/y58xJ/

Upvotes: 0

Zoltan Toth
Zoltan Toth

Reputation: 47687

With your HTML structure you can try this - DEMO

alert ( document.querySelector( "span" ).firstChild.nodeValue );

Upvotes: 1

Related Questions