0

I can get this done by using jquery but I need to get it done by using javascript. I am like a beginner in javascript. I need to get text node from div.

Div contains text node and then span and again text node in it. I can get text node inside div by using firstChild but how to get span text node.

HTML

<div id="test">
12345799
<span>my name </span>
</div>

Script

document.getElementById('test').firstChild.nodeValue
Barmar
  • 669,327
  • 51
  • 454
  • 560
Jitender
  • 7,057
  • 25
  • 92
  • 193

2 Answers2

1

Try this:

document.getElementById('test').getElementsByTagName('span')[0].nodeValue
Barmar
  • 669,327
  • 51
  • 454
  • 560
  • That's not what the question says, it says _how to get span text node_. – Barmar Apr 02 '14 at 14:53
  • If you want to get the text of the parent without any of the children, see this question and the ones linked from it: http://stackoverflow.com/questions/11362085/jquery-get-text-for-element-without-children-text/11362182#11362182 – Barmar Apr 02 '14 at 14:56
1

You can try this

var parent = document.getElementById('test');
string spanText = parent.getElementsByTagName('span')[0].innerText;

if innerText is not supported by your browser, you can also use

parent.getElementsByTagName('span')[0].innerHTML;

Js Fiddle Demo

Sachin
  • 39,043
  • 7
  • 86
  • 102