Learn about some basic but essential DOM methods in JavaScript

The below code is what we’ll use to access and manipulate with our JavaScript DOM methods:
<div id="parent">
<div class="child one"> < /div>
<div class="child children second"> < /div>
<div class="child third"> < /div>
</div>
- Select and element by
id. It will always return 1 element sinceid’s are required to be unique.
document.getElementById(element_id);
Example:
document.getElementById('parent');
2. Select all elements by class name.
document.getElementsByClassName(class_name);
// return all elements with class name as an array
Example:
document.getElementsByClassName('child'); // return child element
document.getElementsByClassName('child children');
// the above returns element which has both child & children class
3. Select and element by tag name
document.getElementsByTagName(tag_name);
Example:
document.getElementsByTagName('div');
4. Select the first element by selector, which returns the first element within the document that matches the specified group of selectors.
document.querySelector(selector);
Example
document.querySelector('.child');
5. Select all elements by selector.
document.querySelectorAll(selector);
Example
document.querySelectorAll('.child');
6. Get child elements of an element.
var parent = document.getElementById('parent');
parent.childNodes; returns NodeList
parent.children; returns HTMLCollection
7. Find the number of children.
var parent = document.getElementById('parent');
parent.childElementCount; // 2
8. Find the parent node.
var child = document.querySelector('.child');
child.parentElement;
9. Creating a new DOM element.
var div = document.createElement('div');
10. Creating a text element.
var h1 = document.createTextNode("This is text element");
11. Add an element as a child node as the last sibling of its adjacent nodes.
var parent = document.getElementById('parent');
var div = document.createElement('div');
parent.append(div);
12. Add an element as a child node as the first sibling of its adjacent nodes.
var parent = document.getElementById('parent');
var div = document.createElement('div');
parent.prepend(div);
Thanks 😊 🙏 for Reading 📖.
Follow me JavaScript Jeep🚙💨 .
Please make a donation here. 80% of your donation is donated to someone needs food 🥘. Thanks in advance.