Skip to content

Instantly share code, notes, and snippets.

@potikanond
Last active October 31, 2023 20:59
Show Gist options
  • Save potikanond/a30a3bcedf5038fe651d1db953127c3f to your computer and use it in GitHub Desktop.
Save potikanond/a30a3bcedf5038fe651d1db953127c3f to your computer and use it in GitHub Desktop.
JavaScript DOM Tutotrial #1

JavaScript DOM Tutorial #1

A tutorial from JavaScript DOM manipulation

Adding JavaScript to Website

Inline JavaScript

Add onload="..." action to the body element. The JS code inside will be executed when the page is loaded.

<body onload="alert('Hello Javascript');">
  <h1>Hello Page</h1>
</body>

Inline JS is NOT a good practice.

Internal Javascript

This is done by adding script tag before the tag.

<body>
  <h1>Hello Page</h1>

  <script type="text/javascript">
    alert('This is internal JS.');
  </script>
</body>

External Javascript

We can create the main.js file and put our JS code side.

<body>
  <h1>Hello Page</h1>

  <script src="main.js"></script>
</body>

We can write the following JS inside the main.js.

document.querySelector('h1').innerHTML = "Good Bye";

Note: adding the script tag before and after the body tag can give good vs. error result.

DOM - Document Object Model

Web browser convert the HTML into the tree struction of objects. Let's start with a simple HTML page as followed:

<body>
  <h1 id="title"><strong>Hello Page</strong></h1>

  <input type="checkbox" name="" id="">
  <button class="btn">Click Me</button>

  <ul id="list">
    <li class="item">
      <a href="http://www.google.com">Google</a>
    </li>
    <li class="item">Second</li>
    <li class="item">Third</li>
  </ul>

  <script src="main.js"></script>
</body>

Using the HTML Tree Generator Chrome's extension, you can see the tree of objects representing this page. We can use document object to access the DOM.

// get entire document
document;
// get <html> object
document.firstElementChild;
// get <head>
document.firstElementChild.firstElementChild;
// get <body>
document.firstElementChild.lastElementChild;

// get <h1>
let h1 = document.firstElementChild.lastElementChild.firstElementChild;
h1.innerHTML = 'DOM Manipulation';
h1.style.color = 'red';
console.log(h1.style.color);

// perform click action on the checkbox
document.querySelector('input').click();

Access DOM properties and call DOM methods

Objects inside the DOM can have properties and methods. Properties describe the object while the methods tell what object can do.

To change the Third item into your name, We can use the following JS code.

// get list of items with specified element, class, or id
document.querySelectorAll('li');
document.querySelectorAll('li').length;

// or
document.getElementsByTagName('li');

// get and change the 3rd <li> item
let item = document.querySelectorAll('li')[2];
item.innerText = 'Dome Potikanond';

To select multiple elements by class or tag, we can also use document.querySelectorAll() as well. This kind of methods always return a list of element even there only a single element found.

// select elements by class name, returns a list.
document.querySelectorAll('.btn');
document.getElementsByClassName('btn');

document.querySelectorAll('.item');
document.getElementsByClassName('item');

// select an element by unique id, return a single object.
document.querySelector('#title');
document.getElementById('title');

What if we want to select a link inside the 1st item.

document.querySelector('li a');
document.querySelector('a');

// get object contains both <li> and item in the same element
document.querySelector('li.item');

// get object that is inside id 'list' that contains class 'item'
document.querySelector('#list .item');

// change the 'Google' text to 'red'
document.querySelector('a').style.color = 'red';

Manipulate HTML styles

Use .style.color property to get/set font color. The javascript style properties name is a bit different from CSS properties. You can find HTML DOM Style object at the following link:

https://www.w3schools.com/jsref/dom_obj_style.asp.

The rule of thumb, it use camel case name pattern.

// hide <h1> element
document.querySelector('h1').style.visibility='hidden';
// unhide <h1> element
document.querySelector('h1').style.visibility='';

// change background color of the 'click me' button
document.querySelector('button').style.backgroundColor='yellow';

Separation of concerns

To keep our code tidy, we separate code into HTML, CSS, and JS. Instead of using JS to change style element by element, we should change style based on the CSS .classList property.

// get CSS class list
document.querySelector('button').classList;
// add CSS 'invisible' class to <button>
document.querySelector('button').classList.add('invisible');
// remove CSS 'invisible' class to <button>
document.querySelector('button').classList.remove('invisible');
// toggle 'invisible'
document.querySelector('button').classList.toggle('invisible');

In the style.css we also have the invisible class defined.

.invisible {
  visibility: hidden;
}

.huge {
  font-size: 5rem;
  color: red;
  font-weight: bold;
}

And we can also toggle the huge class on h1 tag.

document.querySelector('h1').classList.toggle('huge');

Manipulation text

The .innerHTML and .textContent are different. With .innerHTML, you can get/set HTML code under the specified element.

document.querySelector('h1').innerHTML;
document.querySelector('h1').innerHTML = '<em>Good Byle</em>';

Manipulate HTML attributes

Everything that are inside the tag other than the tagname itself are attribute. To play with attribute, see the code below:

document.querySelector('a');
document.querySelector('a').attributes;
document.querySelector('a').getAttribute('href');
document.querySelector('a').setAttribute('href','https://www.bing.com');

The Dicee Game

From the following skeleton project, write your own JavaScript to finish the Dicee game.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Dicee</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower|Lobster" rel="stylesheet">

  </head>
  <body>

    <div class="container">
      <h1>Refresh Me</h1>

      <div class="dice">
        <p>Player 1</p>
        <img class="img1" src="">
      </div>

      <div class="dice">
        <p>Player 2</p>
        <img class="img2" src="">
      </div>

    </div>

    <script src="main.js"></script>

  </body>

  <footer>
    www 🎲 App Brewery 🎲 com
  </footer>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My DOM Website</title>
</head>
<body>
<h1 id="title"><strong>Hello Page</strong></h1>
<input type="checkbox" name="" id="">
<button class="btn">Click Me</button>
<ul id="list">
<li class="item">
<a href="http://www.google.com">Google</a>
</li>
<li class="item">Second</li>
<li class="item">Third</li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment