DEV Community


Posted on

|DOM| DOM: The World of The DOM

          -Introducing the DOM
          -The Document Object 
          -getElementsByTagName and className
          -querySelector and querySelectorAll
Enter fullscreen mode Exit fullscreen mode

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.


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); 

Enter fullscreen mode Exit fullscreen mode

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); 

Enter fullscreen mode Exit fullscreen mode

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.




Enter fullscreen mode Exit fullscreen mode

Same idea, but returns a collection of matching elements.

Top comments (1)

lifeiscontent profile image
Aaron Reisman

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.


function handleClick(event) {
  const header ='.accordion-header');
  const accordion ='.accordion');
  const body = accordion?.closest('.accordion-body');

  if (header) {
   // if I've clicked inside of the header
   // toggle the display of the body of the accordion
    body.hidden = !body.hidden;

document.documentElement.addEventListener('click', handleClick, true);
Enter fullscreen mode Exit fullscreen mode