Lets's Learn Document Object Model
The " DOM "document object model) allows JavaScript to access the content of a web page.The DOM is like a class monitor, where HTML elements are the like the students of a class.It monitors or keeps track of HTML documents. JavaScript is like class teacher it tell the monitor to do something.
Or in other words JavaScript can manipulate HTML elements with DOM.
Show Me your ID
<h1 id="Hello">Hello</h1>
ID Hello then can be then used to access the heading tag <h1> later by Javascript.
Let's Catch this guy
Now, when we have the name given we can catch this guy and manipulate it. To use this element we use method document.getElementById in our script........( yaa...... ya... Jaavascript).
Lets change the text of this element by the inner HTML property...,
document.getElementById("Hello").innerHTML = "Hye";
also you can assign a variable to this element like this.
var headingElement = document.getElementById("Hello");
Lets make it easy with jquery
What we did above is good but still its difficult to work with built-in DOM functions, to over come this we can use a javascript library called jquery.Jquery is a big library with a lot of uses but we are not going to dive deeper but will just have an introduction it.We will do the same thing as above but this time with Jquery.
To use the jQuery, we load it in browser,
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
The script tag is use to load external javscript or to simply add javascript code.You can find more information here.
The above tag loads the jquery from the jquery site but you can also download the jquery from the site and add it to your webpage locally.We can now use the javascript to do , what we did with built-in DOM functions.
The DOM and jQuery 149
<!DOCTYPE html>
<html>
<head>
<title>Jquery</title>
</head>
<body>
<h1 id="myheading">Hello</h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var newHeading = prompt("New heading here");
$("#myheading").text(newHeading);
</script>
</body>
</html>
Here, we added a <script> tag to the page to load jQuery. Then used prompt to take the new heading,
also assigned it to a variable.
The next line is where we have used jquery to select the element with id "Hello" to do this we have used the $() function. $ ( ) is used to select things in jquery.$() function takes one argument, called a selector string which is then used to select the specified element.Here we have passed the id of the element id "myHeading" to it.
Have you noticed we have used text property instead of innerHTML to change the heading.The text property simply passes text whereas the innerHTML parses HTML in an element.
So here our small introduction to HTML DOM and jquery ends. You can share your thoughts in the comment section.
Comments
Post a Comment