Skip to content
the poor coder

js queryselector find without attribute

Poor Man
Published
Reading time
1 min read
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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC