For example, I need to have a list of all tags that have id
attribute set (it could be any other attribute, id
is just an example).
To get all DOM elements by a data attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[data-id]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.
Document.querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
How it works: First, select the link element with the id js using the querySelector() method. Second, get the target attribute of the link by calling the getAttribute() of the selected link element. Third, show the value of the target on the Console window.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
Try this:
document.querySelectorAll('[id]')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With