Last active
November 23, 2020 14:36
-
-
Save shiftyp/4c0fff91143741deaddeb1b76271826f to your computer and use it in GitHub Desktop.
Document Object Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>My Page</title> | |
<style> | |
li { cursor: pointer } | |
</style> | |
<!-- | |
The first place JS and HTML intersect is a script tag | |
They can include external scripts into the HTML page. | |
The browser processes all tags in top to bottom order | |
and executes any scripts when it gets to their script | |
tag. Here we see a tag that loads an external script, | |
meaning that it comes from another domain. We can use | |
global references defined in this script in the page. | |
--> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> | |
</head> | |
<body> | |
<div id="my-div" /> | |
<script> | |
/* | |
Script tags can also include JavaScript directly in | |
the page. In the example below, we see the opposite | |
side of the equation, the Document Object Model. It | |
allows us to access, traverse, and modify elements, | |
as well as other aspects of the page. Below we have | |
an example where we add some content to my-div, and | |
then traverse the nodes that are created in the DOM | |
*/ | |
const myDiv = document.getElementById('my-div') | |
const myList = document.createElement('ol'); | |
myDiv.appendChild(myList) | |
myList.innerHTML = ` | |
<li tab-index="0" data-value="Good Job!">One</li> | |
<li tab-index="0" data-value="Way To Go!">Two</li> | |
` | |
const myListItems = myList.querySelectorAll('li') | |
myListItems.forEach(li => { | |
li.addEventListener('click', () => { | |
console.log(` | |
${li.getAttribute('data-value')} | |
It's ${moment().format('h')} o'clock. | |
`) | |
}) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment