Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active November 19, 2018 22:51
Show Gist options
  • Save harrisonmalone/6e197e6162a198058a3ec787847c648b to your computer and use it in GitHub Desktop.
Save harrisonmalone/6e197e6162a198058a3ec787847c648b to your computer and use it in GitHub Desktop.
this is a nice example of using class syntax in js, also passing in an element that is created outside of a class (ul)
<!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>Document</title>
<script defer src="script.js"></script>
</head>
<body>
</body>
</html>
// we want to uses classes to represent elements on a page
// create a shelf class that creates a ul and
// attaches itself to an element of your choice on
// the page (this could be body element or a div with an id)
// create a book class that creates a book element (li tag) with a title
// create an addBook method to the shelf class that
// takes a book class and adds it as a child to the ul
// create several books for the bookshelf
class Shelf {
constructor() {
}
static createUl() {
const ul = document.createElement("ul")
return document.body.appendChild(ul)
}
}
const ul = Shelf.createUl()
class Book {
constructor(title) {
this.title = title
}
createLi() {
const li = document.createElement('li')
li.innerText = this.title
ul.appendChild(li)
}
}
harryPotter = new Book("harry potter")
readyPlayerOne = new Book("ready player one")
harryPotter.createLi()
readyPlayerOne.createLi()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment