使用 querySelectorAll 从标签的所有属性中提取值

Extract values from all attributes from a tag with 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 抓取它将 return NamedNodeMap 值,你可以使用 Array.prototype.slice.call 将 NodeLists 转换为数组:

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>