Skip to content

Latest commit

 

History

History
42 lines (31 loc) · 897 Bytes

DOM_manipulation.md

File metadata and controls

42 lines (31 loc) · 897 Bytes

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';

We can also create elements

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

We can set attributes on elements

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

We can add event listeners to elements:

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