digital dreamscapes - by somnath pan
Welcome to our JS DOM tutorial! In this tutorial, we'll cover the fundamental JS DOM concepts and methods to interact with web pages.
This JS DOM tutorial assumes that you have a basic knowledge and understanding of HTML, CSS, and JavaScript, if you're new to these topics, consider exploring our html-basics tutorial, css-basics tutorial, and js-basics tutorial, before proceeding to this JS DOM tutorial
The JS DOM (Document Object Model) is a programming interface for HTML and XML documents.
by using DOM you can manipulate html elements using js and add functionality to your website.
Use document.getElementById()
,to select an element with a similar iddocument.querySelector()
,this selector allows you to select an element by its class name,or id or tag name and document.querySelectorAll()
this selects all elements with matching xlass or id.
const element = document.getElementById('id');
const element = document.querySelector('.class');
const elements = document.querySelectorAll('tag');
Use element.textContent
, element.innerHTML
, and element.setAttribute()
to manipulate elements.
element.textContent = 'New text';
element.innerHTML = 'New HTML
';
element.setAttribute('attribute', 'value');
textContent and innerHTML
helps you to set the text content of an element
setAttribute
allows you to dynamically add Attributes such as classnames and IDs to an element,it takes 2 parameters,one is the attribute you want to set and its value
Use addEventListener()
to respond to user interactions.
element.addEventListener('click', function() {
console.log('Element clicked!');
});
the function,adds an event listener to an element,which,allows us to perform specific tasks,when an event occurs,such as,when a button is clicked.
addEventListener function takes 2 parameters,the event name(i.e,"click","input" etc),and a call back function which triggered when the event occurs
Use document.createElement()
and element.remove()
to create and remove elements.
const newElement = document.createElement('tag');
element.remove();
to add the created element to a parent element,you will use the appendChild()
//select the parent
const parent =
document.getElementById('parent');
//create an element
const element =
document.createElement("p");
//set text for the element
element.innerHTML = "hello,world";
//append to to the parent
parent.appendChild(element)
Congratulations! You've learned the basic JS DOM concepts and methods. Practice building your own web page using this tutorial as a reference. In the next tutorial, we'll explore advanced JS DOM topics.
document.getElementById()
, document.querySelector()
, and document.querySelectorAll()
to select elements.element.textContent
, element.innerHTML
, and element.setAttribute()
to manipulate elements.