Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 319
user2513846 Avatar asked Sep 11 '17 14:09

user2513846


People also ask

How do I get the value of a querySelector element?

Use the querySelector() method to get an element by a name attribute, e.g. document. querySelector('[name="first_name"]') . The method returns the first element in the DOM that matches the provided selector. If no element matches the selector, null is returned.

How do I select an element with querySelector?

The querySelector() method returns the first child element that matches a specified CSS selector(s) of an element. Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead.


1 Answers

Just use the getAttribute method of the image element:

var dataSrc = elem.querySelector('img').getAttribute('data-src');
like image 198
Jared Smith Avatar answered Nov 12 '22 14:11

Jared Smith