Get element in vanilla JavaScript Vanilla JS
There are multiple ways you can get/select an element in JavaScript. Here is how to get an element by id, class, tag, name, data-attribute or other attribute in vanilla JavaScript.
Get element by id
There are 2 ways to get an element by id in JavaScript. You can use document.querySelector();
and include the # symbol to specify an id just like with CSS selectors or use document.getElementById();
which is the older way.
document.querySelector('#id-here');
// getElementById
document.getElementById('id-here');
Get element by class
Since document.querySelector();
you can use any CSS selector to target elements with JavaScript so to get an element by class you include a dot just like with CSS to specify a class name.
If an element has multiple classes, you can target that element with both classes as long as you make sure there is no space in between them. If there is a space between the classes, you'll actually be selecting any elements with the second class that are inside an element with the first class.
document.querySelector()
returns only the first element that matches the selector. If you want to select multiple elements by class, you can use document.querySelectorAll()
and pass in the class to get all elements by class. document.querySelectorAll()
returns a NodeList which you can then loop over.
elements.forEach(function(item) {
console.log(item);
});
Get element by tag name
You can get an element by tag name with document.querySelector()
and using a tag selector.
You can select multiple elements by tag name with document.querySelectorAll()
or document.getElementsByTagName()
.
let paragraphs = document.querySelectorAll('p');
paragraphs.forEach(function(item) {
console.log(item);
});
// getElementsByTagName
let paragraphs = document.getElementsByTagName('p');
for (const paragraph of paragraphs) {
console.log(paragraph);
}
Get element by attribute
You can get an element by attribute using an attribute selector with document.querySelector()
. Attribute selectors are enclosed in square brackets and include both the attribute name and the value.
Get element by name
You can get an element by name using the name attribute selector.
To get multiple elements by name, you can use document.querySelectorAll()
or document.getElementsByName()
.
let items = document.querySelectorAll('[name="name-here"]');
items.forEach(function(item) {
console.log(item);
});
// getElementsByTagName
let items = document.getElementsByName('name-here');
for (const item of items) {
console.log(item);
}
Get element by data-attribute
You can get an element by data attribute by using the data attribute selector for your specific data attribute.
Get focused element
You can get the currently focused element in JavaScript with document.activeElement
.
Thanks for reading.
Ryan
Published on 24 Aug 2022