最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get all images in a div using vanilla JS - Stack Overflow

programmeradmin1浏览0评论

I'm doing some plex interprocess JS on unknown pages so jquery is out of the question. How do I get all images within a div provided I have the ref of the div?

Something like :

document.getElementsByTagName("img")

But only within a div.

I'm doing some plex interprocess JS on unknown pages so jquery is out of the question. How do I get all images within a div provided I have the ref of the div?

Something like :

document.getElementsByTagName("img")

But only within a div.

Share Improve this question edited Aug 18, 2016 at 17:34 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Aug 18, 2016 at 17:31 Robin RodricksRobin Rodricks 114k147 gold badges414 silver badges617 bronze badges 1
  • 4 thatDiv.getElementsByTagName("img")? – Sebastian Simon Commented Aug 18, 2016 at 17:33
Add a ment  | 

3 Answers 3

Reset to default 5

You would just search for the div - let's make that it has an id of myDiv:

document.getElementById("myDiv").getElementsByTagName("img");

You could use querySelectorAll() :

var all_imgs = document.querySelectorAll('#div_id img');

If you have the reference of the div you could use it as :

var all_imgs = my_div.querySelectorAll('img');

Hope this helps.

Simply call getElementsByTagName on your <div> element:

var div = document.getElementById("myDiv");
var images = div.getElementsByTagName("img");

or use querySelectorAll:

var images = div.querySelectorAll("#myDiv img");
发布评论

评论列表(0)

  1. 暂无评论