JavaScript DOM access
getting that HTML with JavaScript
The document
object
document
objectIn JavaScript we can access the document (global) object simply with the reserved keyword document:
The getElement...
methods
getElement...
methodsThen, we can access DOM elements, such as all
<h1>
tags like this:
Note that would grab the object representation and not the content of the <h1>
tags!
getElementById(...)
returns an
Element
object with anid
attribute of...
e.g.
getElementById('redlink')
for all tags withid="redlink"
getElementsByClassName(...)
returns an
HTMLCollection
of any element(s) with aclass
attribute of...
e.g.
getElementsByClassName('redlink')
for all tags withclass="redlink"
we can specify more than one class name, separated by spaces
e.g.
getElementsByClassName('redlink bluelink')
getElementsByTagName(...)
returns an
HTMLCollection
of any element(s) with a tag of...
e.g.
getElementsByTagName('h1')
for<h1>
tags
we can specify more than one tag name, separated by spaces
e.g.
getElementsByTagName('h1 h2')
for both<h1>
and <h2> tags
In order to grab the content of the tag, we would need to use the innerHTML
property on the specific element of each returned HTMLCollection
:
The querySelector method
We can access a DOM element using a CSS-style selector with the querySelector
method:
with
document
we call thequerySelector
methodwe then pass a CSS selector as an argument to that method
assigning the method call to a variable, the method will return an
Element
representing the first element that matches the CSS selectorif no matches found, it will return
null
The querySelectorAll method
We can also access a selection of DOM elements that match a CSS-style selector with the querySelectorAll
method:
with
document
we call thequerySelectorAll
methodwe then pass a CSS selector as an argument to that method
assigning the method call to a variable, the method will return a
NodeList
elements will arrange in the order that they appear in the HTML document, with indices
if no matches found, it will return an empty
NodeList
Like the getElement...
methods, we would use element indices ([0]
, [1]
, [2]
, ...) to grab each instance, and then access its contents via the innerHTML
property:
Note that because we specified "a.navlink
" (and not ".navlink
") in the argument, the navLinks variable won't contain the "p.navlink
" data! Had we used only .navlink
this would happen:
Last updated