Skip to content

Manipulating The DOM

sergio edited this page Dec 17, 2020 · 5 revisions

Manipulating The DOM


window.innerHeight;
// returns the inner height of the browser window.
document.URL //=> http://www.flatironschool.com
document.write("Moof") //=> Removes all existing DOM content, replaces it with "Moof"
document.querySelector('header')
document.querySelector('header').remove()
var language;
//=> undefined
 
typeof language;
//=> "undefined"
 
language = "JavaScript";
//=> "JavaScript"
 
typeof language;
//=> "string"


Selectors

<div>
  <h5 id="greeting">Hello!</h5>
</div>

We could find the h5 element with document.getElementById('greeting').


Main Selectors:

document.getElementById('specific_button')
document.getElementsByClassName('banner_type_div')
document.getElementsByTagName('div')

<body>
  <div>
    <ul class="ranked-list">
      <li>1</li>
      <li>
        <div>
          <ul>
            <li>2</li>
          </ul>
        </div>
      </li>
      <li>3</li>
    </ul>
  </div>

  <div>
    <ul class="unranked-list">
      <li>6</li>
      <li>2</li>
      <li>
        <div>4</div>
      </li>
    </ul>
  </div>
</body>
// get <li>2</li>
const li2 = document.querySelector('ul.ranked-list li ul li')

// get <div>4</div>
const div4 = document.querySelector('ul.unranked-list li div')

<main id="app">
  <ul class="ranked-list">
    <li>1</li>
    <li>2</li>
  </ul>

  <ul class="ranked-list">
    <li>10</li>
    <li>11</li>
  </ul>
</main>
document.getElementById('app').querySelectorAll('ul.ranked-list li')
// => <li>1</li>, <li>2</li>, <li>10</li>, <li>11</li>

const main = document.getElementsByTagName('main')[0]

const div = main.children[1]

// we can call getElementsByTagName() on an _element_
// to constrain the search to its children!
const p = div.getElementsByTagName('p')[0]

p.textContent = "Goodbye!"

NOTE: These methods don't actually return Arrays. An HTMLCollection is actually returned from the first two methods. This is a major point of confusion in JavaScript! the HTMLCollection knows its length like an Array. We can iterate across it with a for...in... loop. But it's not technically an Array. This is definitely one of the "warts" of JavaScript but also shows a really mean-spirited interview question. It is not difficult to turn an HTMLCollection into an actual Array (using a loop, for example) but for our purposes we can treat it as an Array.



Creators

let element = document.createElement('div')

document.body.appendChild(element)
let ul = document.createElement('ul')

for (let i = 0; i < 3; i++) {
  let li = document.createElement('li')
  li.innerHTML = (i + 1).toString()
  ul.appendChild(li)
}

element.appendChild(ul)

innerHTML examples

let element = document.querySelector("p#greeting");
element.innerHTML = 'Hello, DOM!'
let header = document.getElementById("div#header");
header.innerHTML = "<h1>Poodles!</h1><h3>An Essay into the Pom-Pom as Aesthetic Reconfiguration of the Other from a post-Frankfurt School Appropriationist Perspective</h3><p><em>By: Byron Q. Poodle, Esq., BA.</em></p>";

This creates, with JavaScript, in the DOM, the quivalent of:

<div id="header">
  <h1>Poodles!</h1>
  <h3>An Essay into the Pom-Pom as Aesthetic Reconfiguration of the Other from a post-Frankfurt School Appropriationist Perspective</h3>
  <p><em>By: Byron Q. Poodle, Esq., BA.</em></p>
</div>
<br>

innerHTML can be dangerous if you use it like:

content = someTextArea.value
node.innerHTML = `Hi, ${content}!`

as someone may do:

<a href='#' onclick='doSomethingNastyLikeStealCookies'>Click here to claim your prize!</a>

ul.remove()
ul.removeChild(ul.querySelector('li:nth-child(2)'))

<!-- for example -->
<body>
  <h1>List of pets ideal for city-dwellers</h1>
  <div>
    <ul>
      <li><span id="dog">Poodle</li>
      <li><span id="king-cobra">Nag</li>
      <li><span id="mongoose">Joe Mongoose</li>
   </ul>
  </div>
</body>
// examples
el = document.querySelector("span#king-cobra"); 
y = el.parentNode; y.removeChild(el);

// other examples
base = document.getElementsByTagName("li")[0].parentNode; 
item = document.createElement("li"); 
s = document.createElement("span"); 
s.id = "cat"; s.textContent = "Nancy Drew (the cat)"; 
item.appendChild(s); base.appendChild(item)

Change Properties

element.style.backgroundColor = '#27647B';
element.style.textAlign = 'center';
ul.style.textAlign = 'left'

Perhaps the most common way to change how things appear in the DOM is by changing an element's class attribute. As you know from CSS, we often change the way a bit of rendered HTML appears by changing its class attribute: adding a name or removing a name.

element.className = "dog"
element.className = "pet-listing dog"
element.classList.remove("this-is-fine");
element.classList.add("the-room-is-on-fire");
element.id = "labrador"

Clone this wiki locally