繁体   English   中英

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

[英]How to add index attribute and value to selected elements dynamically by traversing all elements inside container

如何遍历容器内的所有元素,找到具有 class 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);
``

使用格式化的 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/

暂无
暂无

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

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