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>
Related
<div class="logo">
<a href="somelink.com">
<img src="someimage.png">
</a>
</div>
I want to change the src,how can I chage this src by using documents.getElementsByClassName.
You can not use getElementsByClassName because you don't have any classes associated with it.
You could however use a querySelector and get the class of the div and find the child that way. So with this html:
<div class="logo">
<a href="somelink.com">
<img src="someimage.png">
</a>
</div>
We can then use:
let img = document.querySelector('.logo img')
img.src = '/path/to/new/image.png'
.logo this is the class to find
img this is the child element of .logo
It doesn't have to be a direct child since there was no >
Once we have gotten that image we then set the new src to something else and the browser will automatically load the new image (assuming it exists).
try this
document.getElementsByClassName('img_ad')[0].src ='your source'
and add 'img_ad' class in the img element
<div class="logo">
<a href="somelink.com">
<img class="img_ad" src="someimage.png">
</a>
</div>
You can give the img tag an id and use:
document.getElementById("someid").src= "path/to/src";
or:
document.querySelector("#someid").src = "path/to/src";
Add an ID to the <img> (Example: id="myImage") and in JavaScript use the following:
document.getElementById("myImage").src = "newImage.png";
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')));
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
});
I have a page I'm using to grab image alt text from a slider. Each image has a different alt text, and I'm trying to pull it into an array and then loop through it to display it.
However when I implement it, it only adds one object to the array as opposed to how ever many it may ACTUALLY have inside the div.
$(document).ready(function () {
var tn_array = $("#rightSlider img").map(function () {
return $(this).attr("alt");
});
for (var i = 0; i < tn_array.length; i++) {
alert(tn_array[i]);
$('#links').append('<a href="#" title="' + tn_array[i] + '" >' + tn_array[i] + '</a><br />');
}
});
Here is the main page that the code grabs the alt text from:
<div id="rightSlider">
<div>
<img src="images/adptvtch_s1_1.jpg" alt="Hearing Aid On A Female's Ear" width="330" height="215" />
</div>
<div>
<img src="images/adptvtch_s1_2.jpg" alt="Hands Reading Braille Book" width="330" height="215" />
</div>
<div>
<img src="images/adptvtch_s1_3.jpg" alt="Man In Wheelchair Reading" width="330" height="215" />
</div>
</div>
I've tried other things such as .each and I can't seem to pinpoint why it's only adding the first alt text and not the other ones. If you guys can help me figure it out, I'd be greatly appreciative.
You don't need additional iteration and an unnecessary array manipulation.
Try this,
var xEle = $('#links');
$("#rightSlider img").each(function() {
xEle.append('<a href="#" title="'+ $(this).attr("alt") +'" >'+ $(this).attr("alt") +'</a><br />');
});
DEMO
I have some markup here that I need to reformat using javascript. Basically, I have this code:
<div id="images">
<img src="01.jpg">
<img src="02.jpg">
<img src="03.jpg">
<img src="04.jpg">
<a id="src" href="01.jpg"></a>
<a id="src" href="02.jpg"></a>
<a id="src" href="03.jpg"></a>
<a id="src" href="04.jpg"></a>
</div>
and I want javascript to rewrite the code so that the images are placed inside the anchors. Like this:
<div id="images">
<a id="src" href="01.jpg"><img src="01.jpg"></a>
<a id="src" href="02.jpg"><img src="02.jpg"></a>
<a id="src" href="03.jpg"><img src="03.jpg"></a>
<a id="src" href="04.jpg"><img src="04.jpg"></a>
</div>
any ideas?
<script>
var div = window.document.getElementById("images");
var anchors = div.getElementsByTagName("A");
var imgs = div.getElementsByTagName("IMG");
for (var i = anchors.length - 1; i >= 0; i--) {
anchors[i].appendChild(imgs[i]);
}
</script>
General strategy:
Get a reference to the "images" div
Create a temporary object to store images, e.g. var imgs = {};
Loop over all img elements within the div. For each element:
Add each element to imgs, using its src as the key
Loop over all a elements within the div. For each element:
Lookup the image from imgs using the element's href attribute
Remove the img from its current location, and re-insert it within the body of the a.