Main content
Course: Computer programming - JavaScript and the web > Unit 6
Lesson 3: DOM access methodsSummary: 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?
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?
- I don't understand what traversing the DOM means. What is a childNode or a firstElemenChild?(96 votes)
- 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)
- 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)- I actually didn't see any documentation for
nextElementChild
, but below is a link to info about "nextElementSibling", which essentially returns the next DOM element (sequentially), at the same level as the element you are acting upon.
So if you had an h1 element followed by an h2 element, and you requestedh1.getNextSibling
, you would get the "h2" element back.
https://developer.mozilla.org/en-US/docs/Web/API/Element/nextElementSibling(4 votes)
- // 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) - What is a node(14 votes)
- 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.(28 votes)
- 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)
- Because sometimes, you'll want to use JS to make it so when, for example, the user clicks, the text changes, or something like that.(17 votes)
- If the NodeList is not "live" as is the HTMLcollection. How is the page then updated ?
Is there a special method ? Thanks!(5 votes)- 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)
- I don't understand the for loop for arguments.(4 votes)
- 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];
thearrayName.length
will be 3, sofor(var i=0; i < arrayName.length; i++)
will loop for i=0, 1, 2, and stop at 3. thusi
can be used for indexing the array elements 0, 1, 2 inarrayName[i]
(6 votes)
- A node is an HTML element. Whenever you nest elements, you create child nodes. Child nodes lie within the parent node (the original HTML tag).
You can orgainize nodes like bullets:1. <html>
A. <head>
a. <meta>
b. <title>
c. <style>
B. <body>
a. <h1>
b. <p>
c. <img>
The ones that are farther to the right are child nodes to the ones that are more towards the left. For example,<p>
is a child node to<body>
.
Or, you can organize these nodes in what looks like a graphic organizer and is called a node tree. Learn about this structure here: https://en.wikipedia.org/wiki/Tree_(data_structure)
Learn more here: http://stackoverflow.com/questions/24974621/what-is-a-node-in-javascript(5 votes)
- I'm confused what are
firstElementChild
lastElementChild
nextElementChild/nextElementSibling
previousElementChild/previousElementSibling
childNodes
childElementCount?(4 votes)- An html page has hierarchies like you saw before, paragraphs inside divs etc, these tags inside other tags are "children" and the tag where the others derive is the "parent". "sibling" is the same level of hierarchy(3 votes)
- Is it necessary to mention the element inside <style> element before we use it in javascript as querySelectorAll?(3 votes)
- 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)