首页 > 解决方案 > 如何通过遍历容器内的所有元素动态地将索引属性和值添加到选定元素

问题描述

如何遍历容器内的所有元素并找到具有类 test-image-class 的锚元素,然后动态添加索引属性和值。

var containerHTML = test &nbsp;&nbsp; <a class ="test-image-class" href="" ><span>testimage</span></a> &nbsp;&nbsp;
     &nbsp;&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;

尝试了以下但它不工作

containerHTML.find('a.test-image-class').each(function(index){
  $(this).attr("index",index);
}                                             
console.log(containerHTML);
``

标签: javascripthtmljquery

解决方案


使用格式化的 HTML:

containerHTML.querySelectorAll('a.test-image-class').forEach(function(elem, index){
    
      $(elem).attr("index",index);
    }); 

您可以访问这个小提琴: https ://jsfiddle.net/asutosh/pjgohn5x/

没有格式化的 HTML:

var containerHTMLStr = 'test &nbsp;&nbsp; <a class ="test-image-class" href="" ><span>testimage</span></a> &nbsp;&nbsp; &nbsp; & 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);

请点击链接: https ://jsfiddle.net/asutosh/a017bmkg/3/


推荐阅读