Best Viewed in Split Screen at 0.5x or Click for Full Screen View
QuerySelector: Selecting DOM elements with Query Selectors
Classlist: Using Class List to manage CSS classes
ForEach: Iterating over and manipulating an array of DOM elements
AddEventListener: Listen and act upon user interaction with event listeners
CreateElement: Create and insert a dynamic element into the DOM
Fetch: Getting External JSON Data with Fetch
As we explain each one, we are going to build on their functionality. In the end we are going to tie together each thing we learned to make a dynamic single page headless app.
Query selector lets you target one specific element, here is an example:
var myHeader = document.querySelector(‘h1’)
Which will return you the first h1 element found as a Node Object.
Query selector All is just like Query Selector, but it returns you all elements in an array, here is an example:
var myListItems = document.querySelectorAll(‘li’)
Which will return every li element found as an array of Node Object.
var myDiv = document.getElementById(‘myDivision’)
It returns a Node Object of the element you are targeting.
That will make the background color of your header one
h1 tag yellow by applying a class to your DOM Node! See a working example here:
That code will make all list items have class yellowBackground applied to them. Very cool!
Event listeners listen to user actions like mouse clicks or keystrokes. When an action is detected, you can run a function. Listeners are the foundation of interactive websites and web applications. Let’s see an example:
This code gives each li a click listener. When the user click an element, the background will turn yellow!
You can listen to input changes, keystrokes, mousedowns, etc, be sure to check out this extensive list of things you can listen to.
The ability to create new HTML realtime make for great dynamic experiences. Let’s have a look at Creating an Element and injecting into the dom realtime. Let’s look at an example:
This new code sets up your click listener to add a new element on click, forever!
We are going to use Zesty.io headless content management system to provide a JSON endpoint of company listing. That can be setup for free, but we already create the content so you can see the JSON at this URL: https://meetupwework.zesty.dev/-/instant/6-faee919add-rp5gbb.json
Let’s see how we can access this information with a code example:
New HTML added to prior example:
This is a bit more code than before, but it’s doing more so that ok :). Notice we are using all of the functionality we learned above to make this happen.
Building the Single Page App
We are now going to make this all look like a real application using examples above, and some CSS magic. See the final code example here:
First presented at the Zesty.io meetup on October 14, 2019.