how to get query selector data attribute in javascript? - 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.

Just use the getAttribute method of the image element:
var dataSrc = elem.querySelector('img').getAttribute('data-src');

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" />

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

document.querySelectorAll() example:
document.querySelectorAll('.className').forEach(elem => console.log(elem.getAttribute('interesting-attribute')));

Related

jQuery Get IDs by Class Name

I have a page of about 15-20 YouTube videos I’d like to dynamically update the img src to point to the YouTube hosted thumbnails. From a logic perspective, I want to find every DIV with a class of “videos”, get the ID of that class and update the image source with the dynamically inserted value, e.g., http://img.youtube.com/vi/DbyNtAQyGs/0.jpg in the first example. All IDs are unique because they are the YouTube video IDs and there is only one img tag under each “videos” class.
This code would run on page load so it would have to be pretty fast to ensure the values are set before the browser passes the each img tag in the DOM. Hoping I can get one of those one liners instead of vars and multiple lines.
<div id="DbyNtAQyGs" class="videos">
<img src="" width="212" height="124" />
</div>
<div id="Fh198gysGH" class="videos">
<img src="" width="212" height="124" />
</div>
Current Code
$('.videos img').attr('src', 'http://img.youtube.com/vi/' + $(this).closest('div').attr('id')); + '/0.jpg');
You can use:
$('.videos img').attr('src', function() { return 'http://img.youtube.com/vi/' + $(this).closest('div').attr('id') + '/0.jpg'; })
Loop through the .videos elements:
$('.videos').each(function(){
var $this = $(this),
_id = $this.attr('id'); // Capture the ID
// Construct the img src
$this.find('img').attr('src', 'http://img.youtube.com/vi/' + _id + '/0.jpg');
});
Bonus: chain in the click event for your anchor:
$this.find('a').click(function(e){
e.preventDefault();
loadPlayer(_id);
}).find('img').attr('src', 'http://img.youtube.com/vi/' + _id + '/0.jpg');
So you can simplify your markup:
<div id="DbyNtAQyGs" class="videos">
<img src="" width="212" height="124" />
</div>

jQuery append an img to every div

I am trying to display a thumbnail image with every thumb class, but currently I am getting the output below where the images are looping inside the href instead. The order of div, href and img must not change. It looks something like this jsfiddle but this isn't fully working of course...
currently getting:
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
<img src="">
<img src="">
</div>
required output:
<div class ='thumb'>
<a href="#" rel="1">
<img src=>
</a>
</div>
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
</div>
my loop:
var thumbnails = [];
$.each(data.productVariantImages,function(key, val){
thumbnails.push(val.imagePath);
});
for(var thumb in thumbnails) {
$('.thumb').append($('<img>').attr({
"src":[thumbnails[thumb]]
}));
}
am i looping it wrongly?
edit:
The thumbnails are part of a dynamic gallery where basically every time a user choose a different option in a dropdown list, the sources for the thumbs are supposed to change accordingly.
current html:
<div class="thumbnail"><?php
foreach($skuDetails['productVariantImages'] as $variantImage){
if(isset($variantImage) && $variantImage['visible']){
?>
<div class="thumb">
<a href="#" rel="1">
<img src="<?php echo $variantImage['imagePath']; ?>" id="thumb_<?php echo $variantImage['id']; ?>" alt="" />
</a>
</div> <?php }}?>
</div>
sample array of thumbnails:
["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
"http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]
sample output:
<div class="thumbnail">
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
</div>
You need to use .each function on .thumb. Something like:
$(document).ready(function(){
$('.thumb').each(function(){
$(this).append($('<img>').attr({"src":[thumbnails[thumb]],}));
});
});
your loop is focused on wrong element. You append img tag to the thumb class. So, the img tags inside the same element. You should create div has thumb class inside the loop, and append it to the thumbnail div. That must like
var div = $(".thumbnail");
$.each(imageArray, function(index, value){
var elem = "<div class='thumb'><a href='#' rel='1'></div>";
div.append($elem);
$('.thumb').append("<img />").attr("src", value);
});
It may be wrong but you should watch the thumbnail element. I cannot write the code to test. But I think the logic must be like this.
If you want that exact structure, I made a demo using plain JavaScript. Enter a number and the thumbClone() function will generate that many. You could probably adapt this function with your existing code easily. I'm in rush, it probably needs refactoring, sorry. :-\
DEMO
function thumbClone(qty) {
var main = document.getElementById('main');
var aFig = document.createElement('figure');
var aLnk = document.createElement('a');
var aImg = document.createElement('img');
aLnk.appendChild(aImg);
aImg.src = "http://placehold.it/84x84/000/fff.png&text=THUMB"
aFig.appendChild(aLnk);
aLnk.setAttribute('rel', '1');
main.appendChild(aFig);
aFig.className = "thumb";
console.log('qty: ' + qty);
var thumb = document.querySelector('.thumb');
for (var i = 0; i < qty; i++) {
var clone = thumb.cloneNode(true);
thumb.parentNode.appendChild(clone);
}
}
You need to use each loop which will get each class rather than getting only one class below is syntax of each loop
$(selector).each(function(){
// do your stuff here
)};
in your case
$('.thumb a').each(function(){
// do your stuff here
$(this).append($('<img />').attr('src',[thumbnails[thumb]]);
)};
Looks like you need to create the entire div structure for each image.
Lets create the below structure dynamically using the max length of the image array and add the image src .
var thumbDivStart = "<div class ='thumb'><a href="#" rel="1">";
var thumbDivEnd = "</a></div>";
var thumbDiv = "";
for (i = 0; i < imageArray.length; i++) {
thumbDiv = thumbDivStart + "<img src="+imageArray[i]+"/>"+
thumbDivEnd;
//Here you can append the thumbDiv to the parent element wherever you need to add it.
}

Add a class to an element with javascript

I was wondering if someone could help me. I'm trying to add .fancy-btn to the below using JavaScript.
<div class="button transparent_2">
<a class="extra-color-3" href="#">Get a quote</a>
</div>
I want .fancy-btn class added to the div container, but cant seem to figure out how to achieve is
Thanks
You need to use .addClass():
$(".transparent_2").addClass('fancy-btn')
see here: https://stackoverflow.com/a/507157/3503886
Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
Then
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Here is a JavaScript only method:
var $a = document.getElementsByClassName("transparent_2");
//assuming there is only 1 element (or is the first)
$a[0].className += " fancy-btn";
JSFiddle

jQuery find closest

I'm trying to get the a href of an list item.
HTML
<div class="popup" style="display: none;">
<div class="product">
<div class="photo">
<a href="" class="sendkleur" id="link69"> <!-- href im trying to reach -->
<img id="product-collection-image-69" src="" alt="Test kleur" class="popup-image69">
</a>
</div>
<a href="" class="sendkleur" id="link69">
<strong>Test kleur</strong>
</a>
<span class="swatchLabel-category">Kleur:</span>
<p class="float-clearer"></p>
<div class="swatch-category-container" style="clear:both;" id="ul-attribute137-69">
<img onclick="listSwitcher();" src="" id="a137-32" class="swatch-category" alt="Beige" width="12px" height="12px" title="Beige">
<img onclick="listSwitcher();" src="" id="a137-36" class="swatch-category" alt="Zwart" width="12px" height="12px" title="Zwart">
</div>
<p class="float-clearer"></p>
</div>
</div>
There are multiple popups on the site and thats what makes it difficult. At first I used this code
var link = jQuery('.photo').find('a')[0].getAttribute("href");
But this ofcourse only returns the href of the first popup. Then I tried this code:
var link = jQuery('.photo').closest('a').attr("href");
But this returned undefined
Then I tried this:
var link = jQuery(this).closest('a').attr("href");
But that also returns undefined
Edit
Here is the whole jQuery code snippet
jQuery(document).ready(function(){
jQuery('.swatch-category-container img').click(function(){
var kleur = jQuery(this).attr('title');
var link = jQuery('.photo').find('a').attr("href");
console.log(link);
link += "?kleur="+kleur;
console.log(link);
jQuery('.photo').find('.sendkleur').attr("href", link);
});
});
Working from the .swatch-category-container img element, you can traverse the DOM to find the required a like this:
$('.swatch-category-container img').click(function() {
var link = $(this).closest('.popup').find('.photo a').prop('href');
// do something with link here...
});
If this is the .swatch-category-container img element then, the anchor is the previous to previous sibling of the ancestor swatch-category-container element
var link = jQuery(this).closest('.swatch-category-container').prev().prev().attr("href");
Since you said multiple popups, the idea would be like this.
1. Get all popups
2. From each popup in all popups
Get the photo href item
$('.popup').each(function() {
var hrefItem = $(this).find('.photo a').attr('href');
//Do your processing with href item
});

adding html element using js

I have generated html content
<a href="/images/img1.jpg" target="_blank">
<img src="/images/img1.jpg" alt="asdsadasdsa" />
</a>
how can I on dom ready use image alt content (in this case asdsadasdsa) and add new attribute title with alt image content, in other words above html should be
<a href="/images/img1.jpg" target="_blank" title="asdsadasdsa">
<img src="/images/img1.jpg" alt="asdsadasdsa" />
</a>
js should target only code which has target="_blank" as part of a href attribute.
Try
$('a[target="_blank"]:has(img[alt])').attr('title', function () {
return $(this).find('img').attr('alt');
});
DEMO - jsfiddle
Reference
:has()
.attr()
.find()
[ ] has-attribute-selector
You can try with this:
var $target = $('a[target="_blank"]');
var $content = $target.find('img').attr('alt');
$target.attr('title', $content);
or this way:
var $target = $('a[target="_blank"]');
$target.each(function(){
$(this).attr('title', $(this).find('img').attr('alt'));
});
Demo Fiddle to try

Categories