简体   繁体   English

如何扫描<span>页面的</span>所有<span>标签并获取或设置内容?</span>

[英]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. 我有下面的代码,该代码扫描页面的所有<input>标记,然后您可以设置该标记的值。

 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 ? 现在,如何使用<span>标记执行同样的操作,我已经知道该标记没有名为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 : 您可以使用Node.textContent来设置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. 关键在.textContent ,它是javascript Node对象的属性,可以根据您的应用程序对其进行读写。 Everything else simply replaced "input" with "span". 其他所有内容都只是用“ span”代替了“ input”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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