且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript中getelementsbytagname和getelementsbyname之间的区别是什么?

更新时间:2022-12-13 14:15:01

假设你有这个HTML:

Suppose you have this HTML :

<input name="test" class="cssclassname">

你得到它

document.getElementsByTagName('input')

document.getElementsByName('test')

document.getElementsByClassName('cssclassname')

此外,您可以在文档以外的元素上调用 getElementsByTagName 。例如,允许以下内容:

Also, you can call getElementsByTagName on elements other than document. For example the following is allowed,

document.getElementsById('foo').getElementsByTagName('bar')

getElementsByName 只能在 document

注意:


  • JavaScript区分大小写,你不能像你在问题中那样编写函数

  • 这些函数不仅仅返回元素而是返回一个实时的 nodeList ,所以你必须迭代结果或取第一个如果你确定它是好的: document.getElementsByTagName('input')[0]

  • the MDN是JavaScript方法的一个很好的文档。你应该阅读 getElementsByTagName getElementsByName

  • JavaScript is case sensitive, you can't write the functions like you did in your question
  • those functions don't return just the element but a live nodeList, so you'll have to iterate over the result or take the first one if you're sure it's good : document.getElementsByTagName('input')[0]
  • the MDN is a good documentation for JavaScript methods. You should read getElementsByTagName and getElementsByName.