Javascript 在 div 标签中通过 id 获取元素的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7171483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:10:08  来源:igfitidea点击:

Simple way to get element by id within a div tag?

javascriptdom

提问by eric2323223

Please forgive me if I repeat the question.

如果我重复这个问题,请原谅我。

I have HTML that all elements inside a div tag has different id, suppose I have already get the reference to the div, is there any simple way to get the element by its id without iterate all elements with that div?

我有一个 div 标签内的所有元素都具有不同 id 的 HTML,假设我已经获得了对 div 的引用,是否有任何简单的方法可以通过其 id 获取元素而不用该 div 迭代所有元素?

here is my sample html:

这是我的示例 html:

<div id="div1" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>
<div id="div2" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>

回答by naveen

You may try something like this.

你可以尝试这样的事情。

Sample Markup.

示例标记。

<div id="div1" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>
<div id="div2" >
    <input type="text" id="edit3" />
    <input type="text" id="edit4" />
</div>

JavaScript

JavaScript

function GetElementInsideContainer(containerID, childID) {
    var elm = {};
    var elms = document.getElementById(containerID).getElementsByTagName("*");
    for (var i = 0; i < elms.length; i++) {
        if (elms[i].id === childID) {
            elm = elms[i];
            break;
        }
    }
    return elm;
}

Demo: http://jsfiddle.net/naveen/H8j2A/

演示:http: //jsfiddle.net/naveen/H8j2A/

A better method as suggested by nnnnnn

nnnnnn 建议的更好方法

function GetElementInsideContainer(containerID, childID) {
    var elm = document.getElementById(childID);
    var parent = elm ? elm.parentNode : {};
    return (parent.id && parent.id === containerID) ? elm : {};
}

Demo: http://jsfiddle.net/naveen/4JMgF/

演示:http: //jsfiddle.net/naveen/4JMgF/

Call it like

叫它像

var e = GetElementInsideContainer("div1", "edit1");

回答by Boontawee Home

var x = document.getElementById("parent").querySelector("#child");
// don't forget a #

or

或者

var x = document.querySelector("#parent").querySelector("#child");

or

或者

var x = document.querySelector("#parent #child");

or

或者

var x = document.querySelector("#parent");
var y = x.querySelector("#child");

eg.

例如。

var x = document.querySelector("#div1").querySelector("#edit2");

回答by Paul

You don't want to do this. It is invalid HTML to have more than one element with the same id. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.

你不想这样做。具有多个具有相同id. 浏览器不会这么好,你会有未定义的行为,这意味着你不知道当你通过那个 id 选择一个元素时浏览器会给你什么,它可能是不可预测的。

You should be using a class, or just iterating through the inputs and keeping track of an index.

您应该使用一个类,或者只是遍历输入并跟踪索引。

Try something like this:

尝试这样的事情:

var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
    if(div2.childNodes[i].nodeName == 'INPUT'){
        j++;
        var input = div2.childNodes[i];
        alert('This is edit'+j+': '+input);
    }

JSFiddle

JSFiddle

回答by jfriend00

A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

一个给定的 ID 只能在一个页面中使用一次。具有相同 ID 的多个对象是无效的 HTML,即使它们位于页面的不同部分。

You could change your HTML to this:

您可以将 HTML 更改为:

<div id="div1" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>
<div id="div2" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>

Then, you could get the first item in div1 with a CSS selector like this:

然后,您可以使用 CSS 选择器获取 div1 中的第一项,如下所示:

#div1 .edit1

On in jQuery:

在 jQuery 中:

$("#div1 .edit1")

Or, if you want to iterate the items in one of your divs, you can do it like this:

或者,如果您想迭代其中一个 div 中的项目,您可以这样做:

$("#div1 input").each(function(index) {
    // do something with one of the input objects
});

If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

如果我不能使用像 jQuery 或 YUI 这样的框架,我会去获取 Sizzle 并包含它的选择器逻辑(它与 jQuery 内部的选择器引擎相同),因为使用一个好的选择器库,DOM 操作要容易得多。

If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

如果我什至不能使用 Sizzle(这将大大降低开发人员的生产力),您可以使用普通的 DOM 函数来遍历给定元素的子元素。

You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

您将使用诸如 childNodes 或 firstChild 和 nextSibling 之类的 DOM 函数,并且您必须检查 nodeType 以确保您只获得您想要的元素类型。我从不那样写代码,因为它比使用选择器库效率低得多。

回答by lukad

In HTML ids should be unique. I suggest you change your code to something like this:

在 HTML 中,id 应该是唯一的。我建议你把你的代码改成这样:

<div id="div1" >
    <input type="text" name="edit1" id="edit1" />
    <input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
    <input type="text" name="edit1" id="edit3" />
    <input type="text" name="edit2" id="edit4" />
</div>

回答by Tygari

A simple way to do what OP desires in core JS.

在核心 JS 中执行 OP 所需的简单方法。

document.getElementById(parent.id).children[child.id];

回答by Tygari

Sample Html code   
 <div id="temp">
        F1 <input type="text" value="111"/><br/>
        F2 <input type="text" value="222"/><br/>
        F3 <input type="text" value="333"/><br/>
        Type <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        </select>
        <input type="button" value="Go" onclick="getVal()">
    </div>

Javascript

    function  getVal()
    {
        var test = document.getElementById("temp").getElementsByTagName("input");
        alert("Number of Input Elements "+test.length);
        for(var i=0;i<test.length;i++)
        {
          if(test[i].type=="text")
          {
            alert(test[i].value);
          }
       }
      test = document.getElementById("temp").getElementsByTagName("select");
      alert("Select box  "+test[0].options[test[0].selectedIndex].text);
    }

By providing different tag names we can get all the values from the div.

回答by Boldewyn

Unfortunately this is invalid HTML. An ID has to be uniquein the whole HTML file.

不幸的是,这是无效的 HTML。ID在整个 HTML 文件中必须是唯一的。

When you use Javascript's document.getElementById()it depends on the browser, which element it will return, mostly it's the first with a given ID.

当您使用 Javascript 时,document.getElementById()它取决于浏览器,它将返回哪个元素,主要是具有给定 ID 的第一个元素。

You will have no other chance as to re-assign your IDs, or alternatively using the classattribute.

您将没有其他机会重新分配您的 ID,或者使用该class属性。