![](/img/trans.png)
[英]jQuery - element is selected by attribute but the index returns value of the elements without attribute
[英]How to add index attribute and value to selected elements dynamically by traversing all elements inside container
如何遍历容器内的所有元素,找到具有 class test-image-class 的锚元素,然后动态添加索引属性和值。
var containerHTML = test <a class ="test-image-class" href="" ><span>testimage</span></a>
<a class = "test-image-class" href="" ><span>testimage</span></a>
these two images are not matching <a class = "test-image-class" href="" ><span>testimage</span></a>
尝试了以下但它不工作
containerHTML.find('a.test-image-class').each(function(index){
$(this).attr("index",index);
}
console.log(containerHTML);
``
使用格式化的 HTML:
containerHTML.querySelectorAll('a.test-image-class').forEach(function(elem, index){
$(elem).attr("index",index);
});
你可以访问这个小提琴: https://jsfiddle.net/asutosh/pjgohn5x/
没有格式化的 HTML:
var containerHTMLStr = 'test <a class ="test-image-class" href="" ><span>testimage</span></a> & nbsp; < a class = "test-image-class" href = "" > < span > testimage < /span></a > & nbsp; & nbsp;these two images are not matching & nbsp; & nbsp; < a class = "test-image-class "href = "" > < span > testimage < /span></a > & nbsp; & nbsp ';
var el = $('<div></div>');
var parser = new DOMParser();
var doc = parser.parseFromString(containerHTMLStr, "text/html");
doc.querySelectorAll('a.test-image-class').forEach(function(elem, index) {
$(elem).attr("index", index);
});
console.log(doc.querySelector('body').innerHTML);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.