Module agenda
Query the DOM
Manipulating (manipulating) the DOM
Responding to events
1. query the DOM
Getelementbyid
var x = document.getElementById("anyID");//orvar x = document.querySelector("#anyID");
Getelementbytagname
Queryselector
Queryselectorall
var thing = document.querySelector("#anyID");var list = document.querySelectorAll(".item");
2. manipulating the DOM
Add | modify | remove
Change style
var x = document.querySelector("#anyID");x.innerText = "changed";x.className = "item";//orx.classList.add("item");
Eg: Add a row at a click.
<div class="dom fragment">
(function () { var container; function addItem(item) { item.addEventListener("click", function () { item.className = "item"; item.innerText = "item [li clicked]"; var newItem = document.createElement("li"); newItem.innerText = "item"; item.parentElement.appendChild(newItem); addItem(newItem); }); } WinJS.UI.Pages.define("/pages/dom/dom.html", { // This funciton is called whenever a user navigates to this page.It // populates the page elements with the app's data. ready: function (element, options) { //TODO:Initialize the page here. var pbutton = document.getElementById("domButton"); var title = document.getElementById("domTitle"); container = document.getElementById("domContainer"); title.addEventListener("click", function () { title.innerText = "DOM [span innerText]"; }); pbutton.addEventListener("click", function () { var txt = pbutton.innerText; container.removeChild(pbutton); var btn = document.createElement("button"); btn.textContent = txt; container.appendChild(btn); var newDiv = document.createElement("div"); newDiv.innerHTML = "<ul><li>item</li></ul>"; container.appendChild(newDiv); var domItem = newDiv.querySelector("li"); addItem(domItem); }); } })})
3. Responding to events
Declarative binding
<button id="btn" onclick="handler();">Click!</button>//JavaScriptfunction handler(){ ... }
Programmatic binding
<button id="btn">Click!</button>//JavaScriptfunction handler(){ ... }var b = document.querySelector("#btn");b.addEventListener("click",handler);
We recommend that you use the following method to bind these two events. behavior and performance are separated.