javascript - 使用 querySelectorAll 从标签的所有属性中提取值
问题描述
我正在尝试使用 JavaScript 从标签的属性中获取所有值,但我刚刚收到了数组中的值:<a>
href
var arr = [].slice.call(document.querySelectorAll('[projectaddress]'));
var arr1 = [].slice.call(document.querySelectorAll('[projectname]'));
window.alert(arr[0]);
window.alert(arr1[2]);
<table border=1>
<thead>
<tr>
<th colspan="3">The table header</th>
</tr>
</thead>
<tbody>
<tr>
<td>The table body</td>
<td><a projectaddress="1gj38x" projectname="Test1" href="http://test.com">Web1</a></td>
<td>with three columns</td>
</tr>
<tr>
<td>The table body</td>
<td><a projectaddress="2jur2m" projectname="Test2" href="http://test2.com">Web2</a></td>
<td>with three columns</td>
</tr>
<tr>
<td>The table body</td>
<td><a projectaddress="lkj28x" projectname="Test3" href="http://test3.com">Web3</a></td>
<td>with three columns</td>
</tr>
</tbody>
</table>
解决方案
首先你需要使用attributes
它来获取返回NamedNodeMap
值,你可以使用它Array.prototype.slice.call
来将 NodeLists 转换为 Arrays :
var arr = [].slice.call(document.querySelectorAll('[projectaddress]'));
var arr1 = [].slice.call(document.querySelectorAll('[projectname]'));
Array.prototype.slice.call(arr[0].attributes).forEach(function(item) {
console.log(item.name + ': '+ item.value);
});
Array.prototype.slice.call(arr1[2].attributes).forEach(function(item) {
console.log(item.name + ': '+ item.value);
});
<table border=1>
<thead>
<tr>
<th colspan="3">The table header</th>
</tr>
</thead>
<tbody>
<tr>
<td>The table body</td>
<td><a projectaddress="1gj38x" projectname="Test1" href="http://test.com">Web1</a></td>
<td>with three columns</td>
</tr>
<tr>
<td>The table body</td>
<td><a projectaddress="2jur2m" projectname="Test2" href="http://test2.com">Web2</a></td>
<td>with three columns</td>
</tr>
<tr>
<td>The table body</td>
<td><a projectaddress="lkj28x" projectname="Test3" href="http://test3.com">Web3</a></td>
<td>with three columns</td>
</tr>
</tbody>
</table>
推荐阅读
- c# - 是否可以在 activemq 中以编程方式创建用户而不更改 activemq.xml 文件
- bpmn - “为活动抛出补偿”和“为当前范围抛出补偿”是什么意思?
- spring - 与 SpringBoot 一起使用的微服务架构和工具
- javascript - 无法使用 ES6 在 Canvas 中获得正确的位置(为什么这段代码不能正常工作?)
- reactjs - Ant Design Form 验证必填字段
- vue.js - Vue CLI 错误创建新项目(npm 错误)
- node.js - 使用 jest 对 aws lambda 进行单元测试
- c++ - C++ 不打印字符串
- python - 如何在 Python 输入中捕获特定单词
- html - 打字稿如何更改scss文件中的内容(开关)