The Document Object Model plays a dominant role for all the Web Developers out there, isn't it? Frequent manipulation of the DOM should be an art in the fingertips of the developers. But why is DOM manipulation becoming a key minister in the court of Web developers?
The browsers use the Object Model to structure the web pages logically, which in turn contribute to the elements of HTML on the screen. In simple words, DOM is a structural representation of the objects that are subjected to changes (both in content and structure) on the web. So DOM is nothing but the lord of the objects in your web pages.
How do I manipulate DOM?
- Finding an element isn't a herculean task if you can access the element with the following methods:
.querySelector(): This method stands in par with the first element matching either one or more CSS selectors.
document.querySelector('#tagname') The '#tagname' option picks the first '#tagname 'tag found in the HTML document
.getElementById(): If you require a single element by id then this method would be the right choice for your action.
document.getElementById('#element') Returns the first element that has the id of #element
.getElementsByClassName(): This methods aids in getting two or more objects resulting in an array of elements.
document.getElementByClassName('element') Returns the array
.querySelectorAll(): It is similar to the .querySelector() method. This methods selects all the tags desired by the programmer.
document.querySelectorAll('elementtag') Return all the element tags of the document
- Creating and deleting elements would be another efficient call which can be done through the following methods:
.createElement(): Taking a tag name as input, this method creates a new element.
document.createElement(‘tagname’) creates a new element which can be accessed with the tag name given here
.removeChild(): This method deletes the specific child element.
- Appending a new child element to the previously existing element or a newly created element can be done by
- If you are interested in styling, try out the following command:
document.getElementById(id).style.property = new style
- Replacing an element doesn't take much effort if the following method is executed.
x1.parentNode.replaceChild(x2, x1) newDiv is the new child to be replaced while the div is the existing child that is to be replaced
.addEventListener(): Assigning event listeners to your HTML elements can be done using this method.
- HTML code can have its events defined by using the attributes on tags.
<h1 onclick=”this.innerHTML = ‘Good to see you!!’”>Hello!!</h1> After clicking on the 'Hello!' button, you can comfort your user with the former message on the click of a mouse
Follow our community for more goodies, stickers,