DOM is a programming interface that allows javascript to access and change HTML elements, content, styles and attributes.
note: DOM connects HTML and JavaScript.
1.DOM works :
<h1 id="heading">Hello World</h1>
javascript can access and change that heading using DOM.
document.getElementById("heading").innerHTML = "welcome";
output: welcome //displays welcome instead of Hello World.
2.DOM methods:
getElementById() :select element by ID.
getElementByClassname() : select element by classname.
getElementByTagname() : select element by tagname.
querySelector() : select 1st matching element
querySelectorAll() : select all matching element.
3.Changing HTML content:
<p id="demo" >hello world</p>
<script>
document.getElementById("demo").innerHTML="para";
</script>
4.Changing CSS using DOM :
<h1 id="title">Hello</h1>
<script>
document.getElementById("title").style.color="red;
</script>
5.DOM events :
events are actions performed by the user, such as clicking, typing or moving the mouse.
Example code : Button click.
<button id="btn">Click Me>/button>
<script>
document.getElementById("btn").onclick=function() {
alert("Button Clicked");
}
</script>
Program You can try:
<!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="txt">0</h1>
<button onclick="increament()">+</button>
<button onclick="decrement()">-</button>
<button onclick="reset()">Reset</button>
<script>
let count = 0;
function increament(){
const incBtn = document.getElementById("txt");
count++;
incBtn.innerText = count;
if(count >=10){
document.getElementById("txt").style.color="green";
document.getElementById("txt").style.fontSize="60px"; //fontsize increase
}
else if (count >=5)
{
incBtn.style.color="blue";
document.getElementById("txt").style.fontSize="40px";
}
else if (count <5)
{
incBtn.style.color="red";
document.getElementById("txt").style.fontSize="30px";
}
else
{
document.getElementById("txt").style.color="black";
}
}
function decrement(){
const decBtn = document.getElementById("txt");
count--;
if(count<0)
{ count=0
}
// if(count>0)
// {count--;}
decBtn.innerText = count;
if(count >=10){
document.getElementById("txt").style.color="green";
document.getElementById("txt").style.fontSize="60px"; //fontsize increase
}
else if (count >=5)
{
decBtn.style.color="blue";
document.getElementById("txt").style.fontSize="40px";
}
else if (count <5)
{
decBtn.style.color="red";
document.getElementById("txt").style.fontSize="30px";
}
}
function reset(){
const rst = document.getElementById("txt");
count=0;
rst.innerText = count;
rst.style.color="red";
}
</script>
</body>
</html>
Top comments (0)