简体   繁体   中英

How scan all <span> tags of a page and get or set a content?

I have this following code that scans all <input> tags of a page and then you are able to set you to get a value to this tag.

 var input = document.getElementsByTagName('input'); for (var i = 0; i < input.length; i++) { input[i].value = "123"; } 

Now, how can I do the same with a <span> tag, which I already know does not have a property called value ?

Just use following:

 var spans = document.getElementsByTagName('span'); for (var i = 0; i < spans.length; i++) { var text = spans[i].innerHTML; if (text.length == 0) { spans[i].innerHTML = i; //Some text } } 

You can use Node.textContent to set the text inside span :

 var input = document.getElementsByTagName('span'); for (var i = 0; i < input.length; i++) { input[i].textContent = "123"; } 
 <span></span> <span></span> <span></span> <span></span> <span></span> 

Your question was somewhat confusing, but I'll give my best answer:

Just take your code for the inputs, and change a few key componenents:

var span = document.getElementsByTagName('span');//Replace "input" with "span"

for (var i = 0; i < span.length; i++) {//Again, replacing "input" with "span"

  var textInsideTheSpan = span[i].textContent;//Reading text inside span
  span[i].textContent = "Your text here";//Writing text to the span

}

The key here is in the .textContent , a property of the javascript Node object, which can be read or written to, depending on your application. Everything else simply replaced "input" with "span".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM