Javascript DOM Manipulation
- most javascript is interacting with the DOM
- examples:
- games
- scrolling effects
- dropdown menus
- form invalidations
- interactivity
- animations
- every awesome site ever :'D
- examples:
Defining the DOM
- DOM stands for Document Object Model
- it is the interface between your Javascript and HTML+CSS
- special javascript objects, methods, and functions that we can use to interact with our HTML
and CSS
- can add elements, remove things, change colors, animate things, etc, etc
- the browser turns every HTML tag into a javascript object that we can manipulate
- creates the document object
- everything is stored inside of the document object
- example document object :
Select and Manipulate
- like CSS where we write a selector, with the DOM we write javascript code that goes and **selects ** objects and then we change properties on them...i.e. we manipulate them
- example: change the color of an h1 element
- first select the
h1and same it to a variable ---let h1 = document.querySelector('h1'); - then manipulate it ---
h1.style.color = 'pink';
- first select the
- example: select the
<body>and change its color every secondlet body = document.querySelector('body'); // SELECT let isBlue = false; setInterval(function(){ // MANIPULATE if(isBlue){ body.style.background = 'white'; } else { body.style.background = '#3498db'; } isBlue = !isBlue; }, 1000);
Important Selector Methods
- sample HTML used for examples that follow:
<!DOCTYPE> <html> <head> <title>Selectors Info</title> </head> <body> <h1>Hello</h1> <h1>Goodbye</h1> <ul> <li id="highlight">List Item 1</li> <li class="bolded">List Item 2</li> <li class="bolded">List Item 3</li> </ul> </body> </html> document.getElementById()- takes a string argument and returns the first element with a matching ID
- example:
let highlight = document.getElementById('highlight'); - the return looks like HTML, but it's actually a javascript object
document.getElementsByClassName()- will return a list of all the elements with the class --- looks like an array, but is actually an array-like item called an HTMLCollection --- like a light array, missing some features of arrays
- example:
let bolded = document.getElementsByClassName('bolded');
document.getElementsByTagName()- returns a list of all elements of a given tag
- example:
let li = document.getElementsByTagName('li');
document.querySelector()- returns the first element that matches a given CSS-style selector
- example:
let li = document.querySelector('#highlight'); - example:
let class = document.querySelector('.bolded'); - example:
let h1 = document.querySelector('h1'); - can use nested CSS tags
document.querySelectorAll()- the same as
querySelector()but returns all matching elements instead of just the first one - can still use if there is only one element, it will just be a list of one
- the same as
Manipulating Style
- even though we are changing CSS, this is javascript, so there have to be quotes around the values being assigned
- changes take place immediately
Changing an Element's style
- example of selecting an element & manipulating it:
let tag = document.getElementById('highlight'); tag.style.color = 'blue'; tag.style.border = '10 px solid red'; tag.style.fontSize = '70px'; tag.style.background = 'yellow'; tag.style.marginTop = '200px';- not very DRY code
- although they have to interact, it's better to keep the javascript, CSS, and HTML as separate as possible
Adding/Removing Classes
- if need to make multiple changes, a better way is to create a class with the desired changes in your CSS --- then javascript just adds the class to elements instead of changing all the attributes one by one like in the above example
- alternative example to the one above using
classList:.some-class{ color: blue; border: 10px solid red; fontSize: '70px'; background: 'yellow'; marginTop: '200px'; }let tag = document.getElementById('highlight'); tag.classList.add("some-class"); classListis a read-only list that contains the classes for a given element --- it is not an array- methods:
.classList.add('className').classList.delete('className').classList.toggle('className')- if the element has the class name it will remove it
- if it doesn't have the class name then it will turn it on (add it)
Manipulating Text and Content
textContent
- returns a string of all the text contained in a given element
- the content is everything between the tags but not including the tags
- example:
<p> This is an <strong>awesome</strong> paragraph </p>let tag = document.querySelector('p'); // select the <p> tag tag.textContent // retrieve the textContent // "This is an awesome paragraph" tag.textContent = 'blah blah blah'; // alter the textContent tag.textContent // retrieve the textContent // "blah blah blah"- could just chain it onto
.querySelector
- could just chain it onto
- will get rid of everything in an element and overwrite it, so you will lose any other tags that were contained within the one you're changing
innerHTML
- similar to
textContent, except it returns a string of all the HTMl contained in a given element - example:
<p> This is an <strong>awesome</strong> paragraph </p>let tag = document.querySelector('p'); tag.innerHTML // "This is an <strong>awesome</strong> paragraph" - don't usually use
innerHTMLto alter things because it will have the same problem astextContent - can assign text with HTML and it will render the HTML
document.body.innerHTML = '<strong>HELLO</strong>'will render with theHELLOin bold , whiledocument.body.textContent = '<strong>HELLO</strong>'will render<strong>HELLO </strong>'
Manipulating Attributes
- use
.getAttribute()and.setAttributeto read and write attributes likesrcandhref - example:
<a href="www.google.com">I am a link</a> <img src="logo.png"let link = document.querySelector('a'); link.getAttribute('href'); // "www.google.com" // change href attribute link.setAttribute('href', 'http://www.dogs.com');// <a href="http://www.dogs.com">I am a link</a> // change the image src let img = document.querySelector('img'); img.setAttribute('src', 'corgi.png'); // <img src="corgi.png"> - works on any attributes...
class,id, etc.