If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Summary: DOM access methods

What methods can we use?

We showed how you can use the following methods to find an element or elements in your webpage:

What do they return?

There are two methods that return a single Element object, getElementById and querySelector:
var salsMotto = document.getElementById("salsMotto");
salsMotto.innerHTML = "Math is cool";
The methods getElementsByClassName and getElementsByTagName return an HTMLCollection object that acts like an array. That collection is "live", which means the collection is updated if additional elements with tag name or class name are added to the document.
var teamMembers = document.getElementsByClassName("team-member");
for (var i = 0; i < teamMembers.length; i++) {
   console.log(teamMembers[i].innerHTML);
}
The method querySelectorAll() returns a NodeList, which also acts like an array. That list is "static", which means that the list won't update even if new matching elements are added to the page. Most likely, you won't run into the difference between the two return data types when you're using these methods, but it's good to keep in mind.
var teamMembers = document.querySelectorAll(".team-member");
for (var i = 0; i < teamMembers.length; i++) {
   console.log(teamMembers[i].innerHTML);
}

Accessing with sub-queries

Once you've found an element, you can do subqueries on it using the methods we've just shown. For example:
// find the element with that ID
var salsMotto = document.getElementById("salsMotto");
// find the spans inside that element:
var mottoWords = salsMotto.getElementsByTagName("span");
// log out how many there are
console.log(mottoWords.length);

Traversing the DOM

Another way to access elements is to "traverse" the DOM tree. Each element has properties that point to elements related to it:
  • firstElementChild
  • lastElementChild
  • nextElementChild/nextElementSibling
  • previousElementChild/previousElementSibling
  • childNodes
  • childElementCount
For example:
var salsMotto = document.getElementById("salsMotto");
for (var i = 0; i < salsMotto.childNodes.length; i++) {
   console.log(salsMotto.childNodes[i]);
}
These properties are not available on Text nodes, only on Element nodes. To make sure you can traverse an element, you can check its nodeType/nodeValue properties. You likely will not need or want to use DOM traversal, but it is another option available to you.

Want to join the conversation?

  • old spice man green style avatar for user Sanneke Heijker
    I don't understand what traversing the DOM means. What is a childNode or a firstElemenChild?
    (96 votes)
    Default Khan Academy avatar avatar for user
    • aqualine tree style avatar for user Eswag
      childNode is an element inside of another element. The first child is the first element inside of an element. An example of a childNode would be the strong tag in:
      <p><strong>Text text text.</strong></p>
      (162 votes)
  • leaf red style avatar for user Dustin Partridge
    I'm also having difficulty understanding the DOM traverse method. If you were to use the "firstElementChild" to replace elements in a class...would it replace all "first elements" to the class assigned?

    I don't get how to use "nextElementChild" and "previousElementChild". Are there examples that can be provided...this seems to be a confusing enough topic that maybe shouldn't be introduced in such a quick manner.
    (39 votes)
    Default Khan Academy avatar avatar for user
  • starky tree style avatar for user Mo
    // ok i dont get that part (can someone explain plz) :

    To match ID or selectors that do not follow the CSS syntax (by using a colon or space inappropriately for example), you must escape the character with a back slash. As the backslash is an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector):
    <div id="foo\bar"></div>
    <div id="foo:bar"></div>

    <script>
    console.log('#foo\bar') // "#fooar"
    document.querySelector('#foo\bar') // Does not match anything

    console.log('#foo\\bar') // "#foo\bar"
    console.log('#foo\\\\bar') // "#foo\\bar"
    document.querySelector('#foo\\\\bar') // Match the first div

    document.querySelector('#foo:bar') // Does not match anything
    document.querySelector('#foo\\:bar') // Match the second div
    </script>
    (7 votes)
    Default Khan Academy avatar avatar for user
  • hopper cool style avatar for user Moses Finlay
    What is a node
    (14 votes)
    Default Khan Academy avatar avatar for user
    • purple pi purple style avatar for user Alex
      HTML can be viewed as a tree. Every tag is parsed by the browser, and a DOM object is created. Tags that are inside this tag are considered to be this DOM Object's child elements. In the end you get a hierarchy of objects that have parents and children. In Computer Science such hierarchies are called Trees.
      Every object in this tree is called a Node.
      The object that has no parent is called a Root Node.
      The objects that have no children are called Leaf Nodes.

      In this case, <html> tag creates the Root Node for the web page. It contains 2 other nodes: <head> and <body>. The <head> node contains many leaf nodes like <link> or <script> or <meta> or <title>.
      Note that I used <tag> to refer to nodes, just so that you would understand that this is created from HTML. Actual Node Names don't contain the <> symbols, and are upper case, in the DOM tree.
      (27 votes)
  • female robot grace style avatar for user lsult240
    I don't see the point of JS to change text within a webpage...Why would I use that to change the content of my webpage instead of fixing the HTML?
    (12 votes)
    Default Khan Academy avatar avatar for user
  • aqualine ultimate style avatar for user René Broekhoven
    If the NodeList is not "live" as is the HTMLcollection. How is the page then updated ?
    Is there a special method ? Thanks!
    (5 votes)
    Default Khan Academy avatar avatar for user
    • piceratops ultimate style avatar for user Ana B. Sanchez-Prieto
      OK. When you call for a collection of elements with the document.getElementsByClassName or document.getElementsByTagName, the list is "alive". That means that if after you have created the array you create a new element with the same class or tag name, that alement will be automatically added to your array.
      But that doesn't apply to the querySelectorAll. Therefore if after creating your list with the querySelectorAll method you add a new element of the same sort, that element won'b be added in your list. If you want it to be added, you have to either "push" that element in the list or refill the list by repeating the querySelectorAll.
      (13 votes)
  • mr pink green style avatar for user Sh. Alhabshi
    I don't understand the for loop for arguments.
    (4 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Jim E
      If you need to loop through every element of an array, you can get the array length with the arrayName.length. So if you have an array like var arrayName = [2, 4, 9]; the arrayName.length will be 3, so for(var i=0; i < arrayName.length; i++) will loop for i=0, 1, 2, and stop at 3. thus i can be used for indexing the array elements 0, 1, 2 in arrayName[i]
      (6 votes)
  • aqualine ultimate style avatar for user Vishana
    what is a node?
    (4 votes)
    Default Khan Academy avatar avatar for user
  • purple pi purple style avatar for user vikas
    Is it necessary to mention the element inside <style> element before we use it in javascript as querySelectorAll?
    (3 votes)
    Default Khan Academy avatar avatar for user
    • leaf blue style avatar for user KCF
      No, absolutely not. A style for an element is never necessary. It is only there to "style" the page. As long as you have the correct id's or classes on the element you want to select, you should be good to go. The querySelectorAll(); is there to let you have the same selectors you use in CSS too, but you don't need any calls in the actual CSS for it to work.
      (5 votes)
  • male robot johnny style avatar for user jdcabarbosa
    In the previous challenge, to "replace the words while retaining their capitalization ('doth' to 'does', 'Doth' to 'Does')". What would be the best solution? I tried this but it is not working:

    '// Step 1: Store all doth that are inside lis in dothEls
    var dothEls = document.querySelectorAll("ul .doth");

    // Step 2: Iterate through them and change doth to does
    for (var i = 0; i < dothEls.length; i++) {
    dothEls[i].innerHTML = "does";
    }
    // step 3: capitalizing the first two
    for (var j = 0; j <= dothEls[1]; j++) {
    dothEls[j][0].toUpperCase();
    }'
    Any suggestions? Thanks!
    (4 votes)
    Default Khan Academy avatar avatar for user