Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get < span > value?

Tags:

javascript

There are a piece of code,but can not use <id> tag.

So,how do I get to the <span> 1 2 3 4?

<div id="test">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
<div>
like image 242
suannai Avatar asked Aug 21 '12 09:08

suannai


2 Answers

Try this

var div = document.getElementById("test");
var spans = div.getElementsByTagName("span");

for(i=0;i<spans.length;i++)
{
  alert(spans[i].innerHTML);
}
like image 86
yogi Avatar answered Nov 01 '22 05:11

yogi


var test = document.getElementById( 'test' );

// To get the text only, you can use "textContent"
console.log( test.textContent ); // "1 2 3 4"

textContent is the standard way. innerText is the property to use for legacy IE. If you want something as cross browser as possible, recursively use nodeValue.

like image 29
Florian Margaine Avatar answered Nov 01 '22 03:11

Florian Margaine