JS Dom
JS Dom
JavaScript and HTML are two different things. HTML is markup and JavaScript is code. So how do you get
JavaScript to interact with the markup in your page? You use the Document Object Model.
When you load a page into the browser, the browser parses the HTML and creates an internal model of
your document that contains all the elements of your HTML markup.
Your JavaScript can interact with the DOM to get access to the elements and the content in them.
JavaScript can also use the DOM to create or remove elements (among a number of other things we’ll be
getting to).
When JavaScript modifies the DOM, the browser updates the page dynamically, so you see new content on
your page.
JavaScript can change the content, change the style, change the attribute of an HTML element
JavaScript can add and delete new HTML elements
There are two steps to perform all the above task
Get the element to change the content, attribute or style
Change it
var i=document.getElementById("i1");
b. getElementByTagName()
var i=document.getElementsByTagName("h2");
c. getElementByClassName()
var i=document.getElementsByClassName("c1");
var i=document.getElementById("i1");
i.innerHTML=”JavaScript Content”;
OR we can find the element by its tag name or class name and modify its content
var i=document.getElementsByTagName("h2");
i[0].innerHTML=”JavaScript Content”;
i.style.color=”purple”;
Events are generated by the browser when "things happen" to HTML elements.
<doctype html>
<html>
<head>
<title>Evaent</title>
</head>
<body>
<p id="pid"
onclick="change()">Click Me</p>
<script>
var
pid=document.getElementById("pid")
;
function change(){
pid.innerHTML="you did it";
}
</script>
</body>
</html>
Exercise one write HTML5 and javaScript that changes an image src attribute on click
event.
Checkevent.htm
<doctype html>
<html>
<head>
<title>Event</title>
</head>
<body>
<fieldset>
<legend><p id="pid" onclick="change()">Click Me</p></legend>
<form>
NAME: <input type="text" id="input" onchange="function2()"
placeholder="enter more than two characters">
<p id="result"></p>
<input type="button" id="m" onmouseover="mouseover()"
value="mouseover" onmouseout="mo()">
<p id="result"></p>
</form>
</fieldset>
<script>
var pid=document.getElementById("pid");
function change(){
pid.innerHTML="you did it";
}
function function2(){
var r=document.getElementById("input");
if(r.value.length <= 2)
//alert("that is not a name");
var result=document.getElementById("result").innerHTML=r.value+" is
not a name";
else
var result=document.getElementById("result").innerHTML="THANK YOU
"+r.value;
}
function mouseover(){
var m=document.getElementById("m");
m.style.color="blue";
}
function mo(){
var m=document.getElementById("m");
m.style.color="white";
}
</script>
</body>
</html>