Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Javascript ch8


Published on

  • Be the first to comment

  • Be the first to like this

Javascript ch8

  1. 1. HFJS – BookReview Ch8Brady Cheng
  2. 2. Agenda GetHTML Element Update the HTML Element DOM(Document Object Model)
  3. 3. Get HTML element getElementByID getElementByTagName<body> <img id=“img1” src=“img1.png” alt=“first image”/> <img id=“img2” src=“img2.png” alt=“second image”/> <img id=“img3” src=“img3.png” alt=“third image”/></body> document.getElementById(“img1”); document.getElementByTagName(“img”)[0];
  4. 4. Update the HTML Element  Use innerHTML property to update<head><script type="text/javascript"> function updateText() { document.getElementById("text").innerHTML = "Hello, JS world!"; }</script></head><body> <p id="text" onclick="updateText();"> Hello, world!</p></body> Output: Hello, world! -> Hello, JS world!
  5. 5. DOM  DOM(document object model) is a concept to organize our html as a tree- like structure document html<head> …</head><body> head body <p id="text"> Hello, world!</p></body> p Hello, world!
  6. 6. DOM Every block is a node Upper node is the parent of lower node Two types of node document  Element html  Text Parent of head/body head body Child of html p Hello, world!
  7. 7. DOM Some properties to describe nodes  nodeValue  nodeType document  childNode html  fisrtChild  lastChild head body p Id=textId Hello, world !alert(document.getElementById("textId").firstChild.nodeValue);
  8. 8. DOM Some functions to operate nodes  removeChild();  createTextNode();  appendChild(); We use DOM to implement the aforementioned updateText() function
  9. 9. DOM Use innerHTMLdocument.getElementById("text").innerHTML = "Hello, JS world!"; Use DOMwhile(node.firstChild) node.removeChild(node.firstChild);var new_node = document.createTextNode("Hello, JS world!");node.appendChild(new_node); Output: Hello, world! -> Hello, JS world!