Working with the Window and Document Object Model (DOM) - SelfishHellfish/JS_Ref GitHub Wiki
there exist several browser objects that may be accessed using javascript
the window object
console.log(x)
or console.log(window.x)
, where x = innerHeight, outerHeight, innerWidth, outerWidth, localStorage, sessionStorage, document (the DOM), open etc.
localStorage.setItem('key1', 1000);
console.log(localStorage.getItem('key1'))
console.log(window)
for entire list
the location object
console.log(location)
the DOM
console.log(document)
each html element is transformed into an object with its own properties, e.g. the content of the first element in the body can be accessed using
console.log(document.body.children[0].textContent)
element object properties can also be changed during execution, e.g. first element in first element in body
console.log(document.body.children[0].children[0].style.backgroundColor = 'red';
traversing the DOM
there are more effective ways of traversing the DOM than by specifying children. more manual methods, however, include:
firstElementChild, lastElementChild, nextElementSibling, parentElement
a better way
console.log(document.getElementsByTagName('li'));
returns an array of li elements
getElementsByClassName, getElementById, getElementByName etc.
the best way
using query selectors i.e. css selectors/the way you refer to elements in css
console.log(document.querySelector('h1'));
filter html by element, #id, .class etc. using css formatting
console.log(document.querySelectorAll('.test'));
to get list of all elements of the class 'test'
create, insert, and delete elements
set new element to variable:
var p = document.createElement('P');
characterize it with:
p.textContent = 'a new paragraph!';
etc.
identify and set to var x
the element where insertion should occur, using query selectors. can then use:
x.appendChild(p)
and x.insertBefore(p, y)
, where y
is the element being prepended
delete the paragraph using:
p.parentElement.removeChild(p);
- cross-browser support
better way for newer browsers:
p.remove()
- use with caution, may not be supported on older browsers
trivia: the DOM consists of nodes, which consist of elements and other things, so parentNode
can be used instead of parentElement
, when working with html elements
dialogs
alert('this is an alert');
, var answer = confirm('are you sure');
, var answer - prompt('please enter your name: ');
better to use modals as they can be styled using css
list of basic node/element methods/properties
list of all html element objects. go to 'H' section
cheat sheet