Search code examples
javascriptselectors-api

Extract values from all attributes from a tag with querySelectorAll


I'm trying to obtain all the values from the attributes for the <a> tag with JavaScript but I just received the href in the array:

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>


Solution

  • first you need grab using attributes it will return NamedNodeMap value, you can use Array.prototype.slice.call for converting NodeLists to 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>