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.
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.
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.
Just use the getAttribute
method of the image element:
var dataSrc = elem.querySelector('img').getAttribute('data-src');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With