Skip to content

Latest commit

 

History

History
47 lines (35 loc) · 1.34 KB

DOM_manipulation.md

File metadata and controls

47 lines (35 loc) · 1.34 KB

Basic DOM manipulations

Using JavaScript we can access and manipulate the Document Object Model (DOM). We access the DOM through a global object called document.

HTML

<body>
  <div id="hello"></div>
</body>

A common method to access the DOM is by giving a HTML element an ID, and then using the document method getElementById()

const x = document.getElementById('hello');

Now we have stored a reference of how that HTML element is accessed through the DOM object. We can use this to manipulate the element.

x.innerHTML = 'hello';

See the result of what this code changes here and play with it yourself

We can also create elements

const a = document.createElement('li');
x.appendChild(a);

See the result of what this code changes here and play with it yourself

We can set attributes on elements

a.setAttribute('id', 'hackyourfuture');

See the result of what this code changes here and play with it yourself

We can add event listeners to elements:

turnLeftButton.addEventListener('click', function () {
   turn('left');
});

See the result of what this code changes here: and play with it yourself