Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Document Object Model (DOM)

Posted in Javascript, javascript interview questions, JQuery, Jquery interview questions

DOM is a hierarchy of HTML tags. It represents arrangement of HTML tags in a web page. The DOM provides the information needed for JavaScript to communicate with the elements on the web page. The DOM also provides the tools necessary to navigate through, change, and add to the HTML on the page.

HTML Document:
HTML document

The above HTML document can be represented in the form of a document tree which is called “document object model” is shown below. Each leaf on the tree is called as node which directly relates to each element on a page. When a node appears inside another node of a tree it is considered as a child node of that node.

Structure of DOM:
DOM

JavaScript provide several ways to select DOM elements, change style of the elements, remove element from DOM, add elements to DOM.

How Do I Access the DOM?

To access DOM elements use JavaScript in-built functions.

Example:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id=" header">This is header</h1>
<script>
  var x=document.getElementById("header");
  alert(x.innerHTML);
</script>

</body>
</html>

There are several document functions to select DOM elements like document.getElementsByTagName(), document.createElement(“div”) etc.

Problem with JavaScript Selectors:

To select DOM elements using JavaScript, developers need to write huge code. JQuery solves these problems and provides easy-to-use, cross-browser compatible ways of selecting and working with page elements. We can use JQuery Selectors to modify above code. JQuery reduces developer’s efforts to select and perform any operation on DOM elements.

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
  alert($("#header").html());
});
</script>

</head>
<body>
<h1 id=" header">This is header</h1>
</body>
</html>