TechBubbles Microsoft Technology BLOG

Basic DOM Interactions

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

image

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");

image

You can add an event listener to a button something like below

image

image

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

Add Comment

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud