This Post will cover the basics of selecting elements and manipulating elements in the DOM.
What is DOM
DOM stands for Document Object Model. It is an object oriented representation of a web page.
DOM represents the HTML or XML documents as tree of nodes .
Let's understand the above image.
let's see how we can select and manipulate these nodes.
1. Selecting elements
We'll dicuss 4 ways to select an HTML element
- getElementById
- getElementByName
- getElementByClass
- QuerySelector
getElementById
Div is a HTML element. It has an id attribute, id is used to uniquely identify an element in the DOM.
To select an element by its id we use document.getElementById() method.
getElementById() returns an element object if an id exists. If there is no element with that id then it will return null.
Once the element is selected we can manipulate it ,add styles to it.
Some elements in HTML have name attribute. Unlike id, name doesn't have to be unique.
Multiple elements can have same name value.
to access element by name we use getElementByName().This will return a NodeList.
HTML elements can have class attribute.To access the element by class we use getElementByClass().This will return HTML collection
querySelector
It can be used to select elements with id or class.
To select an element by id we use '#' and for class we use '.'
2. Manipulating elements
Now that we know how to select an element from the DOM in manupulating elements we will see how to add or remove an element from the DOM.
Adding new element to the DOM
To add a new element in the DOM we have to follow 3 steps .
step 1. creating the new element.
step 2. creating the text node.
step 3. adding element into the DOM.
let's see how to write javascript for above 3 steps.
In DOM and style inspector you'll be able to see the div element has been added in the body and inside div element text is added.
Removing elements from the DOM
To remove an element we first have to select it by its id,class or name.
In the below image you can see that there is a span with id bye.
to select and then remove the span below is tha javascript code.
To remove we use remove().This will remove the element from the DOM.
✌️
Top comments (2)
Can we use this in angular?
Angular uses Typescript you can't write javascript in angular. You can use templete reference variables or directives in angular.