how to get query selector data attribute in javascript?
Asked Answered
V

4

13

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.

Valiancy answered 11/9, 2017 at 14:55 Comment(5)
var dataSrc = elem.querySelector('img').getAttribute('data-src');Rothman
Try elem.querySelector('img').dataset.srcTymothy
@Jared Smith please submit it as answer as that is exactly what I was looking for! Thanks! :-)Valiancy
@Valiancy done.Rothman
@Valiancy - Take a look for my example - especially how to read multi word data attributes like data-something-else.Tymothy
R
15

Just use the getAttribute method of the image element:

var dataSrc = elem.querySelector('img').getAttribute('data-src');
Rothman answered 11/9, 2017 at 15:17 Comment(0)
T
5

Example - how to read data-* attrs in vanilla JS:

var elm = document.querySelector('any-tag')
var first = elm.dataset.whatever
var second = elm.dataset.somethingElse // camel case for multi-word

console.log(first, second)
<any-tag data-whatever="value1" data-something-else="value2" />
Tymothy answered 11/9, 2017 at 15:27 Comment(0)
K
2

You just need to get it like any other attribute

<div id="test" data-myattr="toto">

</div>

alert(document.getElementById("test").getAttribute("data-myattr"));

JSFIDDLE

EDIT FROM @waldemarice:

HtmlElement contains the dataset property to get attribut prefixed by data-

    <div id="test" data-myattr="toto">

    </div>

  alert(document.getElementById("test").dataset.myattr);

JSFIDDLE

Kilar answered 11/9, 2017 at 14:59 Comment(1)
For data atrributes there is dataset. No need read it as any other attrs.Tymothy
C
0

document.querySelectorAll() example:

document.querySelectorAll('.className').forEach(elem => console.log(elem.getAttribute('interesting-attribute')));
Crankshaft answered 23/7, 2021 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.