简体   繁体   English

在JavaScript中访问特定div下的所有项目

[英]Access all items under specific div in javascript

Hi i want to access all images under some specific div in javascript.My code is : 嗨,我想访问javascript中某个特定div下的所有图像。我的代码是:

<div id="image-container" style="background-image:url(loading.gif)">
        <div class="fade-box" id="image-1"><a href="javascript:GoNext();"><img src="2bscene-logo.gif" alt="" width="330" height="108" border="0" /></a></div>
        <div class="fade-box" id="image-2" style="display: none;"><a href="javascript:GoNext();"><img src="streetgallery-logo.gif" alt="" width="330" height="108" border="0" /></a></div>
        <div class="fade-box" id="image-3" style="display: none;"><a href="javascript:GoNext();"><img src="g4m-logo.gif" alt="" width="330" height="108" border="0" /></a></div>
</div>

While my js code is : 虽然我的js代码是:

var image_slide = new Array('image-1', 'image-2', 'image-3');

I want to get all DIV s based on id dynamically, not having a predefined array. 我想动态获取所有基于id DIV ,而不具有预定义的数组。 How can I do that? 我怎样才能做到这一点?

By pure javascript, you can try: 通过纯JavaScript,您可以尝试:

var arr = document.querySelectorAll('#image-container img');
for(var i=0;i<arr.length;i++){
    console.log(arr[i].getAttribute('src'))
}

On browsers that support querySelectorAll. 在支持querySelectorAll的浏览器上。 (IE8 and up, modern versions of others, not IE7 and down.) - As mentioned in the comment by TJ Crowder (IE8及更高版本,其他版本的最新版本,而不是IE7及更低版本。)-如TJ Crowder的评论中所述

With JavaScript, you can do this easily with the DOM: 使用JavaScript,您可以使用DOM轻松做到这一点:

var container = document.getElementById("image-container");
var child;
var image_slide = [];
for (child = container.firstChild; child; child = child.nextSibling) {
    if (child.id && child.nodeName === "DIV") {
        image_slide.push(child.id);
    }
}

Live Example | 现场示例 | Source 资源

Note that the code above must be run after the elements are already in the DOM. 注意,上面的代码必须在元素已经在DOM中之后运行。 The best way to ensure that is to put the script tag below them in the page (just before the closing </body> element is good). 确保这一点的最佳方法是将script标签放在页面中的它们下面(就在</body>元素结束之前)。

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

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