0

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)

Prashant
  • 937
  • 1
  • 10
  • 23
  • can you add an id to the first span? – btevfik Mar 23 '13 at 20:02
  • document.getElementById("spanId").textContent should work i think. – btevfik Mar 23 '13 at 20:04
  • Yes I can. The task at hand is to programmatically assign IDs to all spans which have direct text under them, and skip those which have just other HTML tags, but no text of their own. Here I asked just the part of the problem I am stuck with. – Prashant Mar 23 '13 at 20:05
  • already tried textContent as I mentioned in my question itself. It gives the text inside the sub-tags as well – Prashant Mar 23 '13 at 20:06
  • yeah i tried it too. doesnt work. – btevfik Mar 23 '13 at 20:06
  • "technical constraints"? Read this: [What are some empirical technical reasons not to use jQuery?](http://stackoverflow.com/q/5099949/1493698) – Antony Mar 23 '13 at 20:16
  • @Antony - I suppose then you have a solution in jQuery? – Prashant Mar 23 '13 at 20:47

3 Answers3

1

With your HTML structure you can try this - DEMO

alert ( document.querySelector( "span" ).firstChild.nodeValue );
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
0

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/

btevfik
  • 3,391
  • 3
  • 27
  • 39
0

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/

Christophe
  • 27,383
  • 28
  • 97
  • 140