Last active
November 19, 2018 22:51
-
-
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)
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"> | |
<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> |
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
// 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