Jitender
Jitender

Reputation: 7971

How to get child element text using only javascript

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

Upvotes: 0

Views: 2613

Answers (2)

Sachin
Sachin

Reputation: 40970

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

Upvotes: 1

Barmar
Barmar

Reputation: 780673

Try this:

document.getElementById('test').getElementsByTagName('span')[0].nodeValue

Upvotes: 1

Related Questions