简体   繁体   English

查找HTMLButtonElement类型的所有DOM元素

[英]Find all DOM elements of type HTMLButtonElement

I would like to scan a page for all DOM elements of type HTMLButtonElement so that I can get their exact position. 我想在页面上扫描HTMLButtonElement类型的所有DOM元素,以便获得它们的确切位置。 I would then use this position to place another button on top. 然后,我将使用该位置在顶部放置另一个按钮。

I've been scanning through all DOM elements by the following code snippet: 我已经按照以下代码片段浏览了所有DOM元素:

var all = document.getElementsByTagName("*");
var temp = document.createElement('button');
for (var i = 0, max = all.length; i < max; i++) {
    //Loop through all[i] to see if it is an object of type HTMLButtonElement
}

As already pointed out in comments, you can simply use: 正如评论中已经指出的那样,您可以简单地使用:

document.getElementsByTagName("button");

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. Element.getElementsByTagName()方法返回具有给定标签名称的元素的实时HTMLCollection。 The subtree underneath the specified element is searched, excluding the element itself. 搜索指定元素下面的子树,不包括元素本身。 The returned list is live, meaning that it updates itself with the DOM tree automatically. 返回的列表是活动的,这意味着它将自动使用DOM树进行更新。 Consequently, there is no need to call several times Element.getElementsByTagName() with the same element and arguments. 因此,无需使用相同的元素和参数多次调用Element.getElementsByTagName()

MDN's article on Element.getElementsByTagName() MDN关于Element.getElementsByTagName()的文章

Be aware though that HTML also has the <input type="button" /> element as well. 请注意,尽管HTML也具有<input type="button" />元素。 If you want to pull these as well, you'd be better off using document.querySelectorAll() which allows us to specify multiple comma-delimited selectors: 如果您还想拉这些,最好使用document.querySelectorAll() ,它允许我们指定多个逗号分隔的选择器:

document.querySelectorAll('button, input[type=button]');

Furthermore, you can also define button behaviour on elements by setting the ARIA attribute role to "button" : 此外,您还可以通过将ARIA属性role设置为"button"来定义元素上的按钮行为:

<div role="button">...</div>

If you also want to pull these, you can also include [role=button] in the above querySelectorAll call. 如果您还想拉这些,还可以在上面的querySelectorAll调用中包含[role=button]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM