简体   繁体   中英

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

How to traverse all the elements inside the container and find anchor element which has class test-image-class and then add index attribute and value dynamically.

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;

tried the following but its not working

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

With Formatted HTML:

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

You may visit this fiddle: https://jsfiddle.net/asutosh/pjgohn5x/

Without Formatted 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);

Please follow the link: https://jsfiddle.net/asutosh/a017bmkg/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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