This post outlines the basic DOM (Document Object Model) interactions such as Querying the DOM, Manipulating the DOM and responding to the events.
Querying the DOM
getElementById
getElementsByTagName
querySelector
querySelectorAll
Example:
var x = document.getElementById("anyID"); //or var x = document.querySelector("#anyID");
querySelector returns the first matched item, where as querySelectorAll returns the list of items that matches the criteria.
var list = document.querySelectorAll(".item");
For example to query the pic element from the below html
<div> <figure id=""> <img src="" alt="demo" /> <figcaption> image caption </figcaption> </figure> </div>
function queryDOM(){ var x = document.getElementById("pic") }
Inside Visual Studio 2012 editor, using JavaScript Console you can debug the DOM element and you can also see their content at run time as shown below
Manipulating the DOM
You can add, remove or edit the HTML elements by doing some DOM manipulations
var x = document.querySelector("#anyID"); x.InnerText = "changed"; x.className = "item"; // or x.classList.Add("item");
You can add an event listener to a button something like below