Introduction
JavaScript DOM is essential part of web development and there are multiple methods to manipulate HTML elements using JavaScript DOM. The Document object module(DOM) can dynamically changed the elements of HTML objects there are lot o cool tings you can do with JavaScript DOM.
The DOM follows the methods
1.document.getElementById(HTMLElementid)
select an HTML element by id and manipulating HTML element.
<h1 id="title"> Hello readers!</h1>
<script>
document.getElementById('title')
</script>
2.document.getElementsByTagName(HTMLtag)
select an HTML element by tag name and manipulating HTML element.
<h1> Hello readers!</h1>
<script>
document.getElementByTagName('h1')
</script>
3.document.getElementsByClassName(HTMLClass)
select an HTML element by class name and manipulating HTML element.
<h1 class="title"> Hello readers!</h1>
<script>
document.getElementByClassName('title')
</script>
The querySelector() method returns the first element that matches a CSS selector. to select all child node we use querySelectorAll() method
Event Listeners in DOM
An event is action occurs in the web browsers, there are multiple action listeners available in javascript
- click event()
<button id="btn">Click Me!</button>
<script>
let btn = document.querySelector('#btn');
function display() {
alert('It was clicked!');
}
btn.addEventListener('click',display);
</script>
when button was pressed it will display alert box which show it was clicked! and we mentioned the click event inside the function display.
There are multiple event are available for manipulating HTML content like mouse event mouseover(), keyevent() and keydown() lot of source are available for listeners.
Example:
<button>change color</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click', () => {
document.body.style.background = "red"
});
</script>
when user click on change color button the body background will automatically change into red colour.
Repositories to start with Javascript DOM projects
Hey, I'm Ganesh 🖐
I write article on web development and sharing valuable resources which might helps you as developer or beginner.
for more content
follow me Ganesh_Patil
You can also connect with me on twitter
to get more content related to web development
Thank you for the support!
Top comments (3)
I think you made a typo,
getElementTagName
should begetElement*sBy*TagName
same thing for ClassName. Also TagName and ClassName returns an array of nodes, while getElementById will return first node on the tree.Also I always wondered, will getElementsByTagName work on custom elements or react components?
yes definitely Luke, It makes code more readable
document.body.style.background