![](/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.