-Introducing the DOM
-The Document Object
-getElementById
-getElementsByTagName and className
-querySelector and querySelectorAll
Introducing the DOM
The DOM allows us to combine JavaScript with HTML to do stuff.
The DOM stands form Document Object Model.
The DOM is a JavaScript representation of a webpage.
It's your JS "window" into the contents of a webpage.
It just a bunch of objects that you can interact with vis JS.
The Document Object
The objects all have certain properties like the type of elements they represent. But then some of them have more specialized things like attribute or a source for an image or inner text for a heading.
Window is a special object that's always available in the browser.
The document object is our entry point into the world of the DOM.
Its contains representations of all the content on a page, plus tons of useful methods and properties.
getElementById
Selecting with JavaScript to single out one element or all elements with a certain class or all elements with a certain type.
Similar to selecting in CSS.
getElementById() returns an element object representing the element whose id property matches the specified string.
var element = document.getElementById(id);
getElementsByTagName and className
The getElementsByTagName method of document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node.
var elements = document.getElementsByTagName(name);
Basically, all we need to do is get elements by tag name and then pass in a tag name so we don't pass in paragraph.
querySelector and querySelectorAll
querySelector is a newer, all-in-one method to select a single element.
document.querySelector('h1');
document.querySelector('#red');
document.querySelector('.big');
querySelectorAll
Same idea, but returns a collection of matching elements.
Top comments (1)
there's also
Element.closest
which can be super helpful when you need to know if there's an element in the tree above the one you're querying with.e.g.