javascript Javascript按名称获取特定元素(父元素)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13905435/
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-10-26 20:07:59  来源:igfitidea点击:

Javascript Getting specific element (of parent) by name

javascriptgetelementsbyname

提问by Fluidbyte

I'm using custom tags to define sections in an application, so I have something like this:

我使用自定义标签来定义应用程序中的部分,所以我有这样的事情:

<mysection>

   <form>
       <input name="myfield">
   </form>

</mysection>

I'm using the following and able to get the tag (printed to console, everything is groovy)

我正在使用以下内容并能够获得标签(打印到控制台,一切都很好)

var parent = document.getElementsByTagName('mysection');

The issue I'm having is finding the child field by name:

我遇到的问题是按名称查找子字段:

var myfield = parent.getElementsByName("myfield");

...as I don't want to pick up on any other 'sections' that might have an input with the name 'myfield'.

...因为我不想接听任何其他可能具有名称为“myfield”的输入的“部分”。

EDIT:

编辑:

var parent = document.getElementsByTagName('mysection')[0];

was suggested and returns to console the section contents, however, getElementsByNamethrows an error:

被建议并返回到控制台部分内容,但是,getElementsByName抛出一个错误:

Uncaught TypeError: Object #<NodeList> has no method 'getElementsByName' 

回答by Travis J

Using getElementsByTagName()and getElementsByName()will return a NodeList, you need to get the first element of the list like this:

使用getElementsByTagName()getElementsByName()会返回一个节点列表,你需要得到列表这样的第一要素:

var parent = document.getElementsByTagName('mysection')[0];
var myfield = parent.getElementsByName("myfield")[0];

Edit

编辑

You were correct, getElementsByNameis not valid for an element. I am unsure how to localize the functionality of it as you are trying to do. It seems that it will only work for document. You may have to write your own implementation of getElementsByNameif you want to use it in a localized scope.

你是getElementsByName对的,对元素无效。我不确定如何在您尝试时本地化它的功能。似乎它只适用于document. getElementsByName如果您想在本地化范围内使用它,您可能必须编写自己的实现。

Second Edit

第二次编辑

To be nice, I made that implementation for you :D Here it is in all its "glory".

说句好听的,我为你做了那个实现 :D 这是它所有的“荣耀”。

Element.prototype.getElementsByName = function (arg) {
    var returnList = [];
    (function BuildReturn(startPoint) {
        for (var child in startPoint) {
            if (startPoint[child].nodeType != 1) continue; //not an element
            if (startPoint[child].getAttribute("name") == arg) returnList.push(startPoint[child]);
            if (startPoint[child].childNodes.length > 0) {
                BuildReturn(startPoint[child].childNodes);
            }
        }
    })(this.childNodes);
    return returnList;
};
var parent = document.getElementsByTagName('mysection')[0];
var myfield = parent.getElementsByName("myfield")[0];

Small fix

小修复

I was incorrectly passing the element and not its children into the recursion. The code above has been edited with the proper argument passed now. See working fiddle: http://jsfiddle.net/js6NP/5/

我错误地将元素而不是它的子元素传递到递归中。上面的代码已经用现在传递的正确参数进行了编辑。见工作小提琴:http: //jsfiddle.net/js6NP/5/

回答by Fluidbyte

I actually found a much more simple way to handle this:

我实际上找到了一种更简单的方法来处理这个问题:

document.querySelectorAll('mysection [name="myfield"]');

Here you can see an example where it only modifies the field inside the section specified: http://jsfiddle.net/fluidbyte/kph6H/

在这里你可以看到一个例子,它只修改指定部分内的字段:http: //jsfiddle.net/fluidbyte/kph6H/

qSA supports modern browsers and is compatible down to IE8, Here's a polyfill to support back to IE7: https://gist.github.com/2724353

qSA 支持现代浏览器并兼容 IE8,这是一个支持 IE7 的 polyfill:https: //gist.github.com/2724353

回答by Cerbrus

Just use an ID instead:

只需使用 ID 代替:

<mysection>
    <form>
         <input name="myfield" id="fieldName">
    </form>
</mysection>
var myfield = document.getElementById("fieldName");

ID's are supposed to be unique on a page. So you shouldn't have trouble accessing the right element.

ID在页面上应该是唯一的。因此,访问正确的元素应该不会有问题。

If you really haveto use name/tagname, getElementsByTagNameand getElementsByNameboth always return a array(A empty one if no element was found). you can access the right element, just like you'd access elements in arrays:
document.getElementsByTagName('mysection')[0];For the first element with tagname mysection.

如果您真的必须使用名称/标记名,getElementsByTagName并且getElementsByName两者都总是返回一个array(如果没有找到元素,则为空)。您可以访问正确的元素,就像访问数组中的元素一样:
document.getElementsByTagName('mysection')[0];对于带有 tagname 的第一个元素mysection

回答by Eduardo Escobar

getElementsByNamewon't work on a DOM element reference. Use querySelectoror querySelectorAllinstead. In example:

getElementsByName不适用于 DOM 元素引用。使用querySelectorquerySelectorAll代替。例如:

var parent  = document.getElementsByTagName('mysection')[0];
var myfield = parent.querySelector("[name='myfield']");