Manipulating the DOM with Javascript

Introduction

Introduction

make element

const myElem = document.createElement('span');

Attributes like classes and the id can be set as well

myElem.classList.add('foo');
myElem.id = 'bar';
myElem.dataset.attr = 'baz';

Can attach to the body

document.body.appendChild(myElem);

After setting the tag will look like this:

<span class="foo" id="bar" data-attr="baz"></span>

changing existing elements

document.querySelector('.class'); // get first element with class of "class"
document.querySelector('#id'); // select the first element with the id of id
document.querySelector('[data-other]'); // select the first element with the data-other attribute
document.querySelectorAll('.multiple'); // return array of all element with the 'multiple' class