javascript Javascript按名称获取子元素

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

Javascript Get Child Element by Name

javascriptdomchildren

提问by Fluidbyte

I'm passing a var elinto a function. elcontains previously grabbed element (using getElementById) and when I console.log elin the function I get the following:

我正在将一个 var 传递给el一个函数。el包含以前抓取的元素(使用 getElementById),当我el在函数中使用 console.log时,我得到以下信息:

enter image description here

在此处输入图片说明

The problem comes in when I try to grab an element inside of the elusing:

当我尝试在elusing 中抓取一个元素时,问题就出现了:

el.getElementsByName('fname');

I get the error:

我收到错误:

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

回答by Pointy

The getElementsByName()API is at the documentobject level. It's not an HTMLElement method.

getElementsByName()API是在document对象层级。它不是 HTMLElement 方法。

You could use querySelectorAll()instead:

你可以querySelectorAll()改用:

var fnames = el.querySelectorAll('[name=fname]');

It's not supported in older browsers however.

但是,旧浏览器不支持它。