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 <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>
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 <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);
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.