6

I am trying to read 'aria-label' attribute of an anchor tag . But i am getting null value since my code reads child element(<use></use>) rather than parent element(<a></a>). Below is my HTML and js code.

HTML

var inputs = document.querySelectorAll("a");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener("click", function(e) {
    console.log(inputs[i].getAttribute("aria-label"));
  });
}
<a href="#" role="menuitem" id="main-6" aria-haspopup="true" aria-label="Choose your country site">
  <svg class="header-redirect--icon-w">
     <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-country"></use>
  </svg>
  <i class="i-globe-w"></i>
</a>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Green Computers
  • 723
  • 4
  • 14
  • 24

1 Answers1

10

Check this one, you need to refer this inside click event callback

var inputs = document.querySelectorAll("a");
console.log(inputs.length);
for(var i = 0; i < inputs.length; i++){
    inputs[i].addEventListener("click", function(e){
        console.log(this.getAttribute("aria-label"));
    });     
}
<a href="#" role="menuitem" id="main-6" aria-haspopup="true" aria-label="Choose your country site">
    <svg class="header-redirect--icon-w">
           <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-country"></use>
    </svg>
    <i class="i-globe-w"></i>
    test
</a>
dwij
  • 694
  • 8
  • 17