<!-- you don't need to touch HTML in this exercise -->
/* it is not required to use CSS in this exercise */
/* BUT I DON'T LIKE FOLLOWING RULES... */
.foo {
color: blue;
}
/*
It is possible to use functions to simplify
the DOM handling.
In this first part of the solution, we
create some PURE FUNCTIONS that can be used
to simplify the creation of a Web Page
*/
// shortener - I personally hate long
// function names :-)
const createText = text =>
document.createTextNode(text)
// this is a very generic utility.
// it can generate any kind of elements
// with an optional text inside
const createNode = (type, text) => {
const el = document.createElement(type)
// this is yet anoter very short
// syntax for a conditional.
text && el.appendChild(createText(text))
return el
}
// So now we can create some specialized
// functions that are easier to use
// later on:
const h1 = text => createNode('h1', text)
const p = text => createNode('p', text)
const img = (src, alt, width) => {
const el = createNode('img')
// I know... I'm nut with short
// conditionals...
//
// If you want to use is with an
// assignment, you have to wrap it
// witn () so that it becomes an
// atomic instruction to Javascript
src && (el.src = src)
alt && (el.alt = alt)
width && (el.width = width)
return el
}
// Another example of a utility
// function that is simply used to
// reduce the amount of code to write
const add = el => document.body.appendChild(el)
/*
Here we can leverage the utility functions
that we wrote to generate a fairly complex
web page in an "easy way".
Don't worry, your will basically never write
code like that for real.
In real Apps you will use frameworks like
React or Vue to hide most of this
complexity away.
Nevertheless, it is important that you
grasp the basics of DOM manipulation so
that you will understand what is going on
when it comes to more elaborated Apps.
*/
add(h1('Hello World'))
add(p('This page is generated with:'))
add(img('https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/1200px-HTML5_logo_and_wordmark.svg.png', 'HTML5', 80))
// Our helper functions return simple DOM
// references, so we can still use any
// Element API manually:
const p1 = p('Another paragraph...')
p1.classList.add('foo')
add(p1)
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.