Skip to content

Instantly share code, notes, and snippets.

@lekhanh1234
Last active August 4, 2016 01:12
Show Gist options
  • Select an option

  • Save lekhanh1234/71e44aa1eac18e97dfd562cfdb15cd64 to your computer and use it in GitHub Desktop.

Select an option

Save lekhanh1234/71e44aa1eac18e97dfd562cfdb15cd64 to your computer and use it in GitHub Desktop.

#Document Object Model

Document Structure

HTML Structure

<!doctype html>
<html>
  <head>
    <title>Home page</title>
  </head>
  <body>
    <h1>Home page</h1>
    <p>This is text</p>
  </body>
</html>

Tree

The Document Structure is held in Tree Structure.
document.documentElement is root

Moving through the Tree

This is a example to check if a word exists in this web or not.

function talksAbout(node, string) {
  console.log(node);
  if (node.nodeType == document.ELEMENT_NODE) {
    for (var i = 0; i < node.childNodes.length; i++) {
      if (talksAbout(node.childNodes[i], string))
        return true;
    }
    return false;
  } else if (node.nodeType == document.TEXT_NODE) {
    return node.nodeValue.indexOf(string) > -1;
  }
}

console.log(talksAbout(document.body, "book"));

Finding Elements

The previous example, we have to go through all tag. Javascript has some methods to select element faster

  • GetElementByTagName
document.documentElement.getElementsByTagName("a")
  • GetElementByClassName
document.documentElement.getElementsByClassName("image")
  • GetElementById
document.documentElement.getElementsById("ContentWrapper")

Changing the Document

  • removeChild
document.body.getElementsByTagName("div")[0].remove()
  • appendChild
var newpTag = document.createElement("p");
document.body.appendChild(newpTag);
  • insertBefore
<p>One</p>
<p>Two</p>
<p>Three</p>

<script>
  var paragraphs = document.body.getElementsByTagName("p");
  document.body.insertBefore(paragraphs[2], paragraphs[0]);
</script>

Creating Node

  • createElement
var newElement = document.createElement("div");
  • createTextNode
var newTextNode = document.createTextNode("hello");

Query Selector

  • querySelectorAll(selector)
document.querySelectorAll("div");
document.querySelectorAll(".class");
document.querySelectorAll("#id");
  • Select the direct children of an element
document.querySelectorAll("div > p");

querySelector / querySelectorAll cannot change the given document

Exercise

Make a table

var MOUNTAINS = [
  {name: "Kilimanjaro", height: 5895, country: "Tanzania"},
  {name: "Everest", height: 8848, country: "Nepal"},
  {name: "Mount Fuji", height: 3776, country: "Japan"},
  {name: "Mont Blanc", height: 4808, country: "Italy/France"},
  {name: "Vaalserberg", height: 323, country: "Netherlands"},
  {name: "Denali", height: 6168, country: "United States"},
  {name: "Popocatepetl", height: 5465, country: "Mexico"}
];

if (typeof module != "undefined" && module.exports)
  module.exports = MOUNTAINS;

console.log(MOUNTAINS)

function buildTable(mountains){
  var dom = document.createElement("table");
  var head = document.createElement("tr")
  for (property in mountains[0]) {
    var thTag = document.createElement("th");
    thTag.appendChild(document.createTextNode(property));
    head.appendChild(thTag);
  }
  dom.appendChild(head);

  mountains.forEach.call(mountains, function(mountain){
    var element = document.createElement("tr")
    for (property in mountain) {
      var thTag = document.createElement("td");
      thTag.appendChild(document.createTextNode(mountain[property]));
      element.appendChild(thTag);
    }
    dom.appendChild(element);
  });
  
  dom.style.textAlign = "left";

  return dom;
}

document.body.appendChild(buildTable(MOUNTAINS));

byTagName

Build an own function can select all tag from an element

function byTagName(node, tagName) {
    var result = [];
    var recurse = function(node, tagName) {
        if (node.nodeType == document.TEXT_NODE || node.tagName == undefined)
            return
        if (node.tagName.toUpperCase() == tagName.toUpperCase()) {
            result.push(node);
        }
        if (node.childNodes) {
            for (var i=0; i<node.childNodes.length; ++i) {
                recurse(node.childNodes[i], tagName);
            }
        };
    }
    recurse(node, tagName);
    return result;
}

byTagName(document.body, "p");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment