首页 > 解决方案 > 使用 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>

标签: javascriptselectors-api

解决方案


首先你需要使用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>


推荐阅读