简体   繁体   中英

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. 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:

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. 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. Consequently, there is no need to call several times Element.getElementsByTagName() with the same element and arguments.

MDN's article on Element.getElementsByTagName()

Be aware though that HTML also has the <input type="button" /> element as well. 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('button, input[type=button]');

Furthermore, you can also define button behaviour on elements by setting the ARIA attribute role to "button" :

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

If you also want to pull these, you can also include [role=button] in the above querySelectorAll call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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