Javascript按名称获取子元素

Javascript按名称获取子元素

问题描述:

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

I'm passing a var el into a function. el contains previously grabbed element (using getElementById) and when I console.log el in the function I get the following:

当我尝试使用以下方法获取 el 中的元素时出现此问题:

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

el.getElementsByName('fname');

我收到错误:

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


getElementsByName() API位于文档对象级别。它不是HTMLElement方法。

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

您可以使用 querySelectorAll()代替:

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

但旧版浏览器不支持此功能。

It's not supported in older browsers however.