What is Dom
It is an document object model and where it used to represent html allowing javascript to access,change and control the structure and style of the webpage
The DOM is the bridge between HTML and JavaScript that lets you dynamically interact with webpage elements.
Common methods
getElementById() finds an element by its unique ID.
getElementsByClassName() collects all elements with a given class name.
getElementsByTagName() collects all elements with a specific tag.
querySelector() finds the first element that matches a CSS selector.
querySelectorAll() finds all elements that match a CSS selector.
createElement() makes a new HTML element.
appendChild() adds a new child element to a parent.
removeChild() deletes a child element from a parent.
innerHTML changes or gets the HTML content inside an element.
style.property changes the CSS style of an element.
addEventListener() attaches an event (like click or hover) to an element.
Common Methods to Get Elements
let byId = document.getElementById("demo");
let byClass = document.getElementsByClassName("text");
let byTag = document.getElementsByTagName("p");
let byName = document.getElementsByName("username");
let byQuery = document.querySelector(".text");
let byQueryAll = document.querySelectorAll("p");
console.log(byId.innerHTML); // Hello
console.log(byClass[0].innerHTML); // World
example:change text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="head1">hi</h1>
<h1 id="head2">hello</h1>
<h1 id="head3">bye</h1>
<button onclick="gettext()">change text</button>
<script>
function gettext(){
const element=document.getElementById("head1");
console.log(element.innerText);
if(element.innerText=="hi"){
element.innerText="payilagam";
}else{
element.innerText="hi";
}
}
</script>
</body>
</html>
Top comments (0)