javascript - 如何通过遍历容器内的所有元素动态地将索引属性和值添加到选定元素
问题描述
如何遍历容器内的所有元素并找到具有类 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);
推荐阅读
- html - HTML / CSS中的主题材料设计
- python - 为什么 cv2.imread() 不存储我的图像文件的名称?
- python-3.7 - 是否可以在一个变量中存储 2 个单独的值?PYTHON
- linux - .NET CORE 3.0 在 linux 上的 docker 中使用 Windows 身份验证是否有效?
- active-directory - 可以通过添加到 AD 组为 AD 用户创建 Skype for business 帐户吗?
- asp.net-core-2.1 - Core 2.0 发布到 IIS,web.config 错误
- forms - 如何在 vue.js 中不使用禁用的情况下制作始终未选中的复选框?
- vue.js - 在导航和组件 Vue 之间滚动
- php - 将数据从 JS 传递到 PHP 不起作用
- string - 将字符串转换为浮点数。列标题中有一个 % 符号