Skip to content
Advertisement

how to get query selector data attribute in javascript?

I have a custom JS function that creates/inject a custom link into all elements in the page when it loads.

Before manipulation:

<div class="myimagediv">
       <img class="img-tag" src="#" data-src="alternative content I need" alt="">
    </div>

and now this custom function manipulates the element:

[].forEach.call(document.querySelectorAll('.myimagediv'), function(elem) {
            old_html = elem.innerHTML;

            new_html = '<a class="customlink" href="' + elem.querySelector('img').src + '">' + old_html + '</a>';
            elem.innerHTML = new_html;
        });

The newly manipulate element:

<div class="myimagediv">
      <a class="customlink" href="this should be the content of my data-src" title="">
          <img class="img-tag" src="#" data-src="alternative content I need" alt="">
      </a>    
    </div>

How can I get the data-src attribute from the IMG tag and inject it into my newly created custom link function?

I should use a var? and then call it, but I cannot grasp how to read the data-src and re-use it.

Any help would be very much appreciated.

Advertisement

Answer

Just use the getAttribute method of the image element:

var dataSrc = elem.querySelector('img').getAttribute('data-src');
Advertisement