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
  • 741,623
  • 53
  • 500
  • 612
Jitender
  • 7,593
  • 30
  • 104
  • 210

2 Answers2

1

Try this:

document.getElementById('test').getElementsByTagName('span')[0].nodeValue
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 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
  • 40,216
  • 7
  • 90
  • 102