我是javascript
的新朋友。如何在span HTML
内部HTML文件中添加ID值。
我的HTML是:
<!DOCTYPE html>
<html>
<body>
<div>Special characters are:<br/>
<span class="We2" datas2="display">Sample Datas are...</span><br/>
<div><span datas2="display">How do I increment the id or class when I dynamically add the content...</span></div>
<div><span datas2="display">when the code actually runs, 10 will get spit out to</span></div>
<span datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
<span datas2class="We2" datas2="display">$$
动态添加内容时如何增加ID或类...
<span datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
</div>
</body>
</html>
我希望输出是:
<!DOCTYPE html>
<html>
<body>
<div>Special characters are:<br/>
<span id="value1" class="We2" datas2="display">Sample Datas are...</span><br/>
<div><span id="value2" datas2="display">How do I increment the id or class when I dynamically add the content...</span></div>
<div><span id="value3" datas2="display">when the code actually runs, 10 will get spit out to</span></div>
<span id="value4" datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
<span id="value5" datas2class="We2" datas2="display">$$
动态添加内容时如何增加ID或类...
<span id="value6" datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
</div>
</body>
</html>
答案 0 :(得分:0)
您需要执行以下步骤:
datas2 = "display"
的元素,可以使用querySelectorAll('[datas2 = "display"]')
j
,该变量将更改与id
串联的value
值的计数,例如value+i
var elem = document.querySelectorAll('[datas2 = "display"]');
var j = 1;
for(var i=0; i< elem.length; i++){
//set id value
elem[i].id = 'value'+j;
j++;
}
<div>Special characters are:<br/>
<span class="We2" datas2="display">Sample Datas are...</span><br/>
<div><span datas2="display">How do I increment the id or class when I dynamically add the content...</span></div>
<div><span datas2="display">when the code actually runs, 10 will get spit out to</span></div>
<span datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
<span datas2class="We2" datas2="display">$$
您将需要对以下代码段中的inspect element
元素使用浏览器<span>
,以检查id
是否正确存在。