简体   繁体   English

使用vanilla JS获取div中的所有图像

[英]Get all images in a div using vanilla JS

I'm doing some complex interprocess JS on unknown pages so jquery is out of the question. 我在未知页面上做了一些复杂的进程间JS,所以jquery是不可能的。 How do I get all images within a div provided I have the ref of the div? 如果我有div的参考,如何获得div中的所有图像?

Something like : 就像是 :

document.getElementsByTagName("img")

But only within a div. 但只在一个div内。

你只需要搜索div - 让它的id为myDiv

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

You could use querySelectorAll() : 您可以使用querySelectorAll()

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

If you have the reference of the div you could use it as : 如果你有div的引用,你可以使用它:

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

Hope this helps. 希望这可以帮助。

Simply call getElementsByTagName on your <div> element: 只需在<div>元素上调用getElementsByTagName

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

or use querySelectorAll : 或使用querySelectorAll

var images = div.querySelectorAll("#myDiv img");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM