NOTE: Hyphenated CSS property names are in the style object as camelCase.
Manipulating CSS Classes
classlist.add
classlist.remove
classlist.toggle
Instead of adding styles to the style object directly, you can write the style rules in a css file under a class name that you will then apply to the element in the DOM.
Adds elements to the end of the parent element's list of children.
<divclass="container"> <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet</p></div>
constparent=document.querySelector('.container')constnewElement=document.createElement('div')newElement.textContent ="Hi I'm a new div"parent.append(newElement)
<divclass="container"> <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet</p> <div>Hi I'm a new div</div> <------</div>
.prepend
Adds elements to the beginning of the parent element's list of children.
<divclass="container"> <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet</p></div>
constparent=document.querySelector('.container')constnewElement=document.createElement('h2')newElement ="Hi I'm a new h2"parent.prepend(newElement)
<divclass="container"> <h2>Hi I'm a new h2</h2> <------ <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet</p></div>
.after
Adds elements as siblings after the element its called on.
<divclass="container"> <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet</p></div>
constsibling=document.querySelector('h1')constnewElement=document.createElement('h2')newElement ="Hi I'm a new h2"sibling.after(newElement)
<divclass="container"> <h1>Hello World</h1> <h2>Hi I'm a new h2</h2> <------ <p>Lorem ipsum dolor sit amet</p></div>
.before
Adds elements as siblings before the element its called on.
<divclass="container"> <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet</p></div>
constsibling=document.querySelector('p')constnewElement=document.createElement('h2')newElement ="Hi I'm a new h2"sibling.before(newElement)
<divclass="container"> <h1>Hello World</h1> <h2>Hi I'm a new h2</h2> <------ <p>Lorem ipsum dolor sit amet</p></div>