js queryselector find without attribute
- Published
- Reading time
- 1 min read
- Length
- 257 words
On this page
How to use JS querySelector to find elements without attributes#
As a web developer, it's common to use the querySelector method to select specific elements from the DOM. However, what if you want to select elements that do not have any attributes?
Using the querySelector method#
The querySelector method allows you to select elements using CSS selectors. To select an element without attributes, you can use the following code:
const elementWithoutAttr = document.querySelector('div:not([class]):not([id])');In this code, we are using the :not() pseudo-class in combination with the attribute selectors [class] and [id] to select div elements without any class or id attributes.
Using the getElementsByTagName method#
Another way to select elements without attributes is by using the getElementsByTagName method. This method returns a list of all elements with a given tag name. To select elements without attributes, you can filter this list using the hasAttribute method. Here's an example:
const elements = document.getElementsByTagName('div');
const elementWithoutAttr = Array.from(elements).filter(element => !element.hasAttribute('class') && !element.hasAttribute('id'))[0];In this code, we are first getting all div elements using the getElementsByTagName method. Then we are converting this list to an array and filtering it using the hasAttribute method to select only those elements without class or id attributes. Finally, we are selecting the first element from this filtered list.
Conclusion#
In this post, we have seen two ways to select elements without attributes using JS querySelector and getElementsByTagName methods. While both methods work, the querySelector method is more concise and easier to read.