I would like to grab all img
tags under an arbitrary level of nested siblings from a specified parent tag but my implementation isn't printing out any el
.
<div class='grand'>
<div>
<img src='1.png'>
</div>
<div>
<div>
<img src='2.png'>
</div>
</div>
<img src='3.png'>
</div>
My implementation so far:
let images = $('div.grand').siblings().find('img')
images.each((i, el) => {
console.log($(el).html()) //prints empty string
})
Essentially, I would like to obtain the same result as the soup.findAll('img')
of BeautifulSoup
in python.
Your code doesn't print out the empty string - it doesn't print anything in the each
, because no elements are matched.
To find elements matching a selector which are a descendant of elements matching another selector, put a space between them. Here, for img
s which descent from .grand
, you'd use .grand img
:
$('.grand img').each((i, el) => {
console.log(el.attribs.src)
});
Result:
1.png
2.png
3.png
You were close: To perform what you need:
$(".grand img").each(function() {
const src = $(this).attr("src")
console.log(src)
})
This takes advantage of $(this)
to access the src
attribute of the referenced object
.grand img
means access ALL children inside the elements with a class of grand
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.