0

I have searched all day and can´t find an answer to my problem.

I have the folowing DIV setup:

<div id="MainDiv1">
    <div id="Galery1">
        <div id="Image" style="width:100px;"></div>
        <div id="Image" style="width:100px;"></div>
        <div id="Image" style="width:100px;"></div>
    </div>
</div>
<div id="MainDiv2">
    <div id="Galery2">
        <div id="Image" style="width:80px;"></div>
        <div id="Image" style="width:80px;"></div>
        <div id="Image" style="width:80px;"></div>
    </div>
</div>

What I need is, with Javascript, to set a variable with the Width of any of the "Image" DIV, but only the ones in the "Galery1". Since they all have the same width any of them will work.

I have tryed:

DIVwidth = document.getElementById("Image");

But this always gives me back 80px, that are from the "Galery2" DIV. I assume I have to give a Path somehow to limit the search into the "Galery1" or "MainDiv1" DIVs.

I can not give unique names to the DIVs.

Any suggestions?

4

2 回答 2

1

首先,它将帮助您了解 id 和类之间的区别:http: //css-tricks.com/the-difference-between-id-and-class/

请记住,您应该将所有 Image ID 元素更改为 Image Classed 元素:

<div id="MainDiv1">
    <div id="Galery1">
        <div class="Image" style="width:100px;"></div>
        <div class="Image" style="width:100px;"></div>
        <div class="Image" style="width:100px;"></div>
    </div>
</div>
<div id="MainDiv2">
    <div id="Galery2">
        <div class="Image" style="width:80px;"></div>
        <div class="Image" style="width:80px;"></div>
        <div class="Image" style="width:80px;"></div>
    </div>
</div>

从图库 1 中选择图像变得很简单:

document.getElementById("Galery1").getElementsByClassName('Image')[0]

document.getElementById("Galery1").getElementsByClassName('Image')将返回匹配元素的数组(具有“Image”类的元素嵌套在 ID 为“Galery1”的元素下)并[0]选择返回数组的第一个索引。


或者,您可以通过执行以下操作简单地选择页面上的第一个图像:document.getElementsByClassName('Image')

于 2013-01-03T20:00:09.297 回答
1

ID 应该是唯一的。IE你不应该超过一个id="Image"

要选择第一个 divGallery2试试这个:

document.getElementById( 'Gallery2' ).getElementsByTagName( 'div' )[0]; // <-- '0' gets first item from array
于 2013-01-03T19:46:20.780 回答