Traversing DOM with javascript - javascript

I have a piece of HTML like this:
<div id="contentblock">
<div id="producttile_137" class="producttile">
<a href="#" class="tile">
<img src="images/Bony A-Booster.jpg" alt="Bony A-Booster - 50 ml">
Bony A-Booster
<span class="price">€10.95</span>
</a>
</div>
<div id="producttile_138" class="producttile">
<a href="#" class="tile">
<img src="images/Bony B-Booster.jpg" blt="Bony B-Booster - 50 ml">
Bony B-Booster
<span class="price">€20.95</span>
</a>
</div>
<div>Aditional info</div>
</div>
I need to get all <img /> sources but with pure Javascript. I can get element by class name document.getElementsByClassName('producttile') but is it possible to traversing in pure JS to <img /> ang get src="" value?

You could use :
document.getElementsByClassName('class_name');
//OR
document.getElementsByTagName('img');
//OR
document.querySelectorAll('img');
All the previous methods are pure javascript and return nodes list so you could loop through them to get the src of every node.
Hope this helps.

You can use the function getElementsByTagName.
function listImages() {
var img = document.getElementsByTagName('img');
for (var i in img) {
if (img[i].src) {
console.log(img[i].src);
}
}
}
<div id="contentblock">
<div id="producttile_137" class="producttile">
<a href="#" class="tile">
<img src="images/Bony A-Booster.jpg" alt="Bony A-Booster - 50 ml">
Bony A-Booster
<span class="price">€10.95</span>
</a>
</div>
<div id="producttile_138" class="producttile">
<a href="#" class="tile">
<img src="images/Bony B-Booster.jpg" blt="Bony B-Booster - 50 ml">
Bony B-Booster
<span class="price">€20.95</span>
</a>
</div>
<div>Aditional info</div>
</div>
Show Images

one possible solution to get img and the src value:
var imgs = document.querySelectorAll('img')
var res = [].slice.call(imgs).map(x=>x.getAttribute("src"))
//or in es5
//.map(function(x){return x.getAttribute("src")})
//[].slice.call is necessary to transform nodeList in array
//otherwise you can use an regular for loop
console.log(res)
<div id="contentblock">
<div id="producttile_137" class="producttile">
<a href="#" class="tile">
<img src="images/Bony A-Booster.jpg" alt="Bony A-Booster - 50 ml">
Bony A-Booster
<span class="price">€10.95</span>
</a>
</div>
<div id="producttile_138" class="producttile">
<a href="#" class="tile">
<img src="images/Bony B-Booster.jpg" blt="Bony B-Booster - 50 ml">
Bony B-Booster
<span class="price">€20.95</span>
</a>
</div>
<div>Aditional info</div>
</div>
wanting to directly select an element based on it's src value you could also do this :
document.querySelector('[src="images/Bony A-Booster.jpg"]')
(assuming there is one element you can use querySlector() instead of querySelectorAll() )

You can use document.getElementsByTagName() to fetch all the img tags as a HTMLCollection. And then, you can iterate over the HTMLCollection and get the src attribute value by using getAttribute() method as below:
const imgElements = document.getElementsByTagName("img");
Array.from(imgElements).forEach(function(element){
console.log(element.getAttribute("src"));
});

Related

Jquery get image src array

I'm making a discord bot with discord.js.
jQuery get the image src
looked for the most relevant article, but it's different from what I'm trying to do.
I'd like to receive several srcs of img in the span tag by array.
<div class="jewel__wrap">
<span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000">
<span class="jewel_img">
<img src="https://xxx/60.png" alt=""> // this src
</span>
<span class="jewel_level">Lv.5</span>
</span>
<span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001">
<span class="jewel_img">
<img src="https://xxx/50.png" alt=""></span> // this src
<span class="jewel_level">Lv.5</span>
</span>
</div>
const jewel = $(".jewel_level").text();
const jewel2 = $(".jewel_img").find('img').attr("src");
console.log("jewel : ", jewel, "jewel2 : ", jewel2);
jewel receives both lv.5 and ex) lv.5lv.5.
jewel2 only receives one src.
How should I bring it?
console
jewel : Lv.5Lv.5 jewel2 : https://xxx/60.png
The problem with jQuery's .attr() is...
Get the value of an attribute for the first element in the set of matched elements
Instead, you can use jQuery's .map() to transform a collection of elements into an array
const sources = $(".jewel_img > img")
.map((_, { src }) => src) // extract property
.get() // get the array out of the jQuery object
console.log("sources", sources)
<!-- minified HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="jewel__wrap"> <span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000"> <span class="jewel_img"> <img src="https://xxx/60.png" alt=""> </span> <span class="jewel_level">Lv.5</span> </span> <span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001"> <span class="jewel_img"> <img src="https://xxx/50.png" alt=""></span> <span class="jewel_level">Lv.5</span> </span></div>
You may even want to treat the text in a similar way and collect all the data into objects
const data = $(".jewel_btn")
.map((_, btn) => {
const $btn = $(btn)
return {
image: $btn.find(".jewel_img img").attr("src"),
level: $btn.find(".jewel_level").text()
}
})
.get()
console.log("data", data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="jewel__wrap"> <span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000"> <span class="jewel_img"> <img src="https://xxx/60.png" alt=""> </span> <span class="jewel_level">Lv.5</span> </span> <span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001"> <span class="jewel_img"> <img src="https://xxx/50.png" alt=""></span> <span class="jewel_level">Lv.5</span> </span></div>

add specific anchor links a class

How I can add to my anchor links a class?
My html code looks like this:
<div class="et_pb_blurb_content">
<div class="et_pb_main_blurb_image">
<a href="video.mp4">
<span class="et_pb_image_wrap">
<img loading="lazy" width="128" height="128" src="2021/02/cover.png" alt="" class="et-waypoint et_pb_animation_off wp-image-17" />
</span>
</a>
</div>
<div class="et_pb_blurb_container">
<h4 class="et_pb_module_header">
Watch
</h4>
</div>
</div>
With javascript code I want achieve like this it adds anchor links class:
<div class="et_pb_blurb_content">
<div class="et_pb_main_blurb_image">
<a href="video.mp4" class="vp-a">
<span class="et_pb_image_wrap">
<img loading="lazy" width="128" height="128" src="2021/02/cover.png" alt="" class="et-waypoint et_pb_animation_off wp-image-17" />
</span>
</a>
</div>
<div class="et_pb_blurb_container">
<h4 class="et_pb_module_header">
Watch
</h4>
</div>
</div>
I use wordpress divi theme and there is not possible add class to anchor video links
Could use something like below:
// grab all the parent items by classname
const linkParents = document.querySelectorAll('.et_pb_module_header');
// iterate over parents
[...linkParents].forEach((parent) => {
// grab the anchor tag from the parent
const link = parent.querySelector('a');
// add your classname to the anchor tag
link.classList.add('vp-a');
});

jquery: how to append DOM element to selector within variable containing other DOM elements

When storing DOM elements in a javascript variable prior to appending them to the actual DOM is there a way with jQuery to select elements inside the variable?
For example,
I have a list of tweets on my page. Every time I click a refresh button I append a new tweet to the list below.
I add the new tweet like follows:
new tweet
<li class="tweet normal-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name"></div>
</div>
<div class="text">Once in a lullaby</div>
<div class="time-stamp" data-time="1322631934000">1322631934000</div>
</div>
</li>
Inside each tweet on the page, not the new tweet yet, I use jQuery to append some elements.
I have:
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
and I append it to the element with the .content class
$(actionsMarkup).appendTo('#tweets .tweet .content');
Now, when I make a new tweet I do the following:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
actionsMark = $(actionsMarkup);
$(newTweet.appendTo('#tweets');
I need to be able to append the actionsMark contents to the div with class .content. However, I can't just reapply my prior statement of
$(actionsMarkup).appendTo('#tweets .tweet .content');
because that puts the markup on all .content divs again, even if it is already there.
Is there a way for me to use selectors to access the DOM nodes in my newTweet variable before I append it to the document object?
I am thinking something like
$(actionsMarkup).appendTo( newTweet, '.content');
If there is no way with selectors to do this then what are some other quick ways?
List of Tweets and Tweet container
<ul id="tweets" class="normal-tweet show-promoted-tweets">
<li class="tweet promoted-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name">Dorothy</div>
</div>
<div class="text">Somewhere over the rainbow</div>
<div class="time-stamp" data-time="1322631934000">3 minutes ago</div>
</div>
</li>
<li class="tweet promoted-tweet" data-user-name="lion">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=lion" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/lion" title="lion">lion</a>
<div class="full-name">Lion</div>
</div>
<div class="text">Way up high,</div>
<div class="time-stamp" data-time="1322631934000">17 minutes ago</div>
</div>
</li>
<li class="tweet normal-tweet" data-user-name="scarecrow">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=scarecrow" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/scarecrow" title="scarecrow">scarecrow</a>
<div class="full-name">Scarecrow</div>
</div>
<div class="text">And the dreams that you dreamed of,</div>
<div class="time-stamp" data-time="1322631934000">32 minutes ago</div>
</div>
</li>
</ul>
You can use .last(), to select the last element after you append your new tweet, like below:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
$(newTweet).appendTo('#tweets');
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
$("#tweets .tweet").last().find(".content").append(actionsMarkup);
});
if you insist to use appendTo(), you can try using :last-child:
$(actionsMarkup).appendTo('#tweets .tweet:last-child .content');
I was looking to see if you can do the same thing, found this question but the existing answer is not useful in my case as i would like to alter the element before adding.
You can create a new dom element in a variable with jQuery and do operations on it as if it is already in the dom before appending it.
Example:
var newTweet = $('<div></div>');
newTweet.addClass('tweet');
newTweet.append('<span class="username"></span>');
newTweet.find('span.username').html('John Doe');
$('body').append(newTweet);
the following will be appended to the body:
<div class="tweet"><span class="username">John Doe</span></div>
Very handy if you are building a reusable interface element (like a dialogue box) with multiple options.

JQuery Parent-Child Selection

I am new to jQuery and am trying to write a script that will run through a menu list and display the correct background image based on the menu item. The menu list is going to be randomly populated so a script is necessary to load the correct image.
The problem is that the attribute where I am able to see which item the menu belongs to is not on the list item itself but on a div contained inside the list item. My question is is it possible to select a child element of the already selected element ?
E.g (the menuli a segment)
$(document).ready( function() {
$(menuli).each( function(index) {
$itemnumber = $(menuli a).attr("href");
switch($itemnumber) {
case 1:
$(this).css("background-image", "image01.jpg");
break;
}
});
});
This is more or less the script I am trying to get, where each list item is iterated through and depending on the href of the link inside the list item a background image is set to that list item.
EDIT
Here is my html:
<div id="divMenuSportGSXSports">
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=468&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl00_lnkSport" href="/Sport/Groups.aspx?IDSport=468&Antepost=0">
<span title="SOCCER">SOCCER</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=520&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl01_lnkSport" href="/Sport/Groups.aspx?IDSport=520&Antepost=0">
<span title="BASEBALL">BASEBALL</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=544&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl02_lnkSport" href="/Sport/Groups.aspx?IDSport=544&Antepost=0">
<span title="CRICKET">CRICKET</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=525&Antepost=0&Tema=Supabets)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl03_lnkSport" href="/Sport/Groups.aspx?IDSport=525&Antepost=0">
<span title="BASKETBALL">BASKETBALL</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=534&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl04_lnkSport" href="/Sport/Groups.aspx?IDSport=534&Antepost=0">
<span title="ICE HOCKEY">ICE HOCKEY</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=523&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl05_lnkSport" href="/Sport/Groups.aspx?IDSport=523&Antepost=0">
<span title="TENNIS">TENNIS</span>
</a>
</div>
</div>
</div>
Yes you can, use find
var parentElement = $('#someElement');
var childElement = parentElement.find('.child'); //where .child should be your child selector
Where as example code is not clear, I just gave answer to your question.
try to change this:
$(this).css("background-image", "image01.jpg");
to this:
$(this).children("div").css("background-image", "image01.jpg");
If you want to target the direct child of the element, better to use children() than find()
Please refer to this: What is fastest children() or find() in jQuery?

Javascript how to get the value of a parent node

hello in the colde below i am trying to get the value of the third span from the img tag
here is the code :
<li class="art1">
<div class="infoArt">
<div class="infoArtTitle"><a name="3224502"></a>Chemise ML rose clair coupe droite motif bicolore</div>
<div class="infoArtPrice">
<br>
<span id="ctl00_mainColumnContent_universeCatalog_rptCatalog_ctl00_lblP" class="artP">39</span><br>
<span id="ctl00_mainColumnContent_universeCatalog_rptCatalog_ctl00_lblRetailerPrice" class="artOldP">90</span><br>
<span id="ctl00_mainColumnContent_universeCatalog_rptCatalog_ctl00_lblAvailability" class="artState">out</span>
</div>
</div>
<div class="imgArt">
<div class="infoWrapper" id="n3224502"><!-- id is new new for mdr -->
</div>
<a href="/vp4/_sales/ha/bufi/FR_0XQNB3L041/ikId3224502.aspx">
<img src="/vp4/_sales/ha/products/ev_3224502.jpg" alt="" style="">
</a>
</div>
<div class="btArt">
<a class="btSheetPdt" href="/vp4/_sales/ha/bufi/FR_0XQNB3L041/ikId3224502.aspx" title="fiche produit">
<span>fiche produit</span>
</a>
<span> </span>
</div>
</li>
I would like to get it from this query to get the out value :
document.getElementsByTagName('img")[0]
then I have no idea what I should do , could you please help.
Thanks.
You can access the third span from the img by:
document.getElementsByTagName("img")[0].parentNode.parentNode.previousSibling.getElementsByTagName("span")[2].innerHTML
You could use the ID of the element:
document.getElementById("ctl00_mainColumnContent_universeCatalog_rptCatalog_ctl00_lblAvailability")[0]
The Span is not inside the img tag in your case. If you're looking for the third span, you can try this
document.getElementsByTagName('span')[2].innerHTML

Categories

Resources