简体   繁体   English

选择具有javascript但不使用jQuery的ID的div的div子对象的img子对象

[英]Selecting img child of div child of div with ID with JavaScript but Without jQuery

I want to gather a fairly complicated wrapped set using JavaScript whilst avoiding having to load the jQuery library (or any other library, eg. Sizzle). 我想使用JavaScript收集一个相当复杂的包装集,同时避免加载jQuery库(或任何其他库,例如Sizzle)。

Within the following HTML I want to form a wrapped set consisting of every img element: 在以下HTML中,我想形成一个包含每个img元素的包装集:

<div id='slider'>

   <div><img src="../../images/rby/rby (30).jpg" width="720" height="507"></div>
   <div><img src="../../images/rby/rby (18).jpg" width="720" height="507"></div>
   <div><img src="../../images/rby/rby (12).jpg" width="720" height="507"></div>

</div>

I've tried using the querySelectorAll() method mentioned in this answer but I'm unable to generalise the lesson to my own specific needs. 我尝试使用此答案中提到的querySelectorAll()方法,但无法将课程概括为我自己的特定需求。 Can someone help perhaps?! 有人可以帮忙吗?

Many thanks. 非常感谢。

Well, the syntax of querySelectorAll() is the same as jQuery's selector syntax. 好吧, querySelectorAll()的语法与jQuery的选择器语法相同。 So, your solution would be: 因此,您的解决方案将是:

// If you want only the <img> elements inside <div> elements:
var my_images = document.querySelectorAll('div#slider div img');

// If you want all images inside div#slider:
var my_images = document.querySelectorAll('div#slider img');

Of course, if you don't mind the lack of IE6 / IE7 support, you're good to go! 当然,如果您不介意缺少IE6 / IE7支持,那就太好了!

Like this (note, cross-browser but may not deal with more complex examples as well as .querySelectorAll might, depending)? 像这样(请注意,跨浏览器,但可能无法处理更复杂的示例,而.querySelectorAll可能取决于)。

var slider = document.getElementById('slider'),
    imgs = slider.getElementsByTagName('img'),
    selected = images = document.querySelectorAll('#slider img');

console.log(imgs);
console.log(selected);

http://jsfiddle.net/h5a4n/1/ http://jsfiddle.net/h5a4n/1/

(Note, the #slider img was stolen shamelessly from am not i am's answer. Not that I couldn't have figured it out on my own... :P ) (请注意, #slider img是不是无耻地被偷走了,不是我的回答。不是我自己#slider img这个问题... :P

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

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