js按id获取元素

时间:2011-04-09 23:21:13

标签: javascript

全部!我有个疑问。我需要通过它的id获取一个元素。我知道我可以使用document.getElementById()或jquery选择器,但我不想使用jquery或任何其他库。我们的想法是仅使用js而不使用库来构建组件。

我遇到了这种情况,代码生成的代码:

<div id="objprop">

    <div id="prop-header"><span>Mi Ventana</span></div>
    <div id="prop_width" style="clear: both;">
        <label style="margin-left: 7px; margin-bottom: 7px; float: left;">Width</label>
        <input type="text" style="float: right; margin-right: 7px; width: 70px;" id="width">
    </div>
    <div id="prop_height" style="clear: both;">
        <label style="margin-left: 7px; margin-bottom: 7px; float: left;">Height</label>
        <input type="text" style="float: right; margin-right: 7px; width: 70px;" id="height">
    </div>
    <div id="prop_left" style="clear: both;">
        <label style="margin-left: 7px; margin-bottom: 7px; float: left;">Left</label>
        <input type="text" style="float: right; margin-right: 7px; width: 70px;" id="left">
    </div>
    <div id="prop_top" style="clear: both;">
        <label style="margin-left: 7px; margin-bottom: 7px; float: left;">Top</label>
        <input type="text" style="float: right; margin-right: 7px; width: 70px;" id="top">
    </div>
</div>

所以,让我想设置输入宽度id的值。我不确定使用document.getElementById,因为可能是html中具有相同id的其他元素。

这是我的怀疑

5 个答案:

答案 0 :(得分:3)

HTML specification表示id只能使用一次。它必须在整个文档中是唯一的。如果您正在处理有效的文档,那么使用document.getElementById()

会感觉很舒服

答案 1 :(得分:2)

根据specifications,元素的id属性在文档中必须是唯一的。因此,只要文档符合规范,使用getElementById()就没有问题。

答案 2 :(得分:1)

“id”属性的值必须在整个页面中唯一。你是对的,因为“getElementById()”必须处理在多个元素上使用的相同“id”值,这是一个问题。这就是你绝对不应该这样做的原因。这就是为什么它被称为“id” - 它是元素的标识符

答案 3 :(得分:0)

我不确定使用document.getElementById,因为可能是html中具有相同id的其他元素。

我必须是唯一的。

http://validator.w3.org/

答案 4 :(得分:0)

感谢。

解决我的问题。我做了以下事情:

我创建了动态元素,所以我添加了一个帖子修复 像这样:this.postfix = new Date()。getTime();

所以,当我必须使用id'width'添加和输入时,我添加了postfix,就像名为'width _'+ postfix一样。所以我可以安全地使用document.getElementById;

由于