Skip to content

Latest commit

 

History

History
104 lines (74 loc) · 2.5 KB

document.md

File metadata and controls

104 lines (74 loc) · 2.5 KB

The Document Object

See also:

The document is a property of the browser window object:

window.document

The document object and some properties:

document

document.head
document.body

document.title
document.URL
document.cookie

Traversing the document tree hierarchy (we need to know about JavaScript arrays):

document.childNodes
document.children
document.children[0].children
document.children[0].children[0]
document.children[0].children[1]

Selections

Selecting elements:

<div id="my-container">
  <p id="my-message">some placeholder content</p>
</div>
<script type="text/javascript">

  // select elements from the DOM by specifying their unique identifiers:
  var myDiv = document.getElementById("my-container")
  var myParagraph = document.getElementById("my-message")

  // manipulate properties of an element:
  myParagraph.innerHTML = "Fun times!"
  myParagraph.style.color = "red"

  // can even create new elements:
  var myHeading = document.createElement("h3")
  myHeading.innerHTML = "This is a heading"
  myDiv.appendChild(myHeading)

</script>

Event-listening

References:

<button id="my-awesome-btn">
  Click Me
</button>
<script type="text/javascript">
  
  var clickCount = 0

  // access the button element from the DOM by specifying its unique identifier
  var myBtn = document.getElementById("my-awesome-btn")

  // define a click event handler function
  function myBtnClick() {
    clickCount = clickCount + 1
    console.log("YOU CLICKED ME", clickCount, "TIMES! :-)")
  }

  // register the handler function to the button's click event
  myBtn.addEventListener("click", myBtnClick, false)
  
</script>