Listings 17.05 and 17.06 - Building HTML with JavaScript
JS Bin
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Listings 17.05 and 17.06</title>
</head>
<body>
<h1>My Movie Ratings</h1>
<div id="movies"></div>
</body>
</html>
JS:
var moviesData = [
{
"title" : "Inside Out",
"summary" : "An emotional adventure inside the head of a young girl."
},
{
"title" : "Tomorrowland",
"summary" : "Recreating the hope and wonder of previous generations."
},
{
"title" : "The Wizard of Oz",
"summary" : "Strangers find friendship and strength on a long walk."
}
];
function getMovieHTML (movie) {
var html = "<h3>" + movie.title + "</h3>";
html += "<p>" + movie.summary + "</p>";
return html;
}
function getMoviesHTML (movies) {
var html = "";
movies.forEach(function (movie) {
html += "<li>" + getMovieHTML(movie) + "</li>";
});
return "<ul>" + html + "</ul>";
}
function render (movies) {
var moviesDiv = document.getElementById("movies");
moviesDiv.innerHTML = getMoviesHTML(movies);
}
render(moviesData);
Listings 17.05 and 17.06 - Building HTML with JavaScript - Tasks 1 to 3
- Add a paragraph element to the page.
- Give the paragraph an id attribute.
- Use JavaScript to display a message in the paragraph with the number of movies.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Listings 17.05 and 17.06</title>
</head>
<body>
<h1>My Movie Ratings</h1>
<p id="numMovies"></p>
<div id="movies"></div>
</body>
</html>
JS:
var moviesData = [
{
"title" : "Inside Out",
"summary" : "An emotional adventure inside the head of a young girl."
},
{
"title" : "Tomorrowland",
"summary" : "Recreating the hope and wonder of previous generations."
},
{
"title" : "The Wizard of Oz",
"summary" : "Strangers find friendship and strength on a long walk."
}
];
function getMovieHTML (movie) {
var html = "<h3>" + movie.title + "</h3>";
html += "<p>" + movie.summary + "</p>";
return html;
}
function getMoviesHTML (movies) {
var html = "";
movies.forEach(function (movie) {
html += "<li>" + getMovieHTML(movie) + "</li>";
});
return "<ul>" + html + "</ul>";
}
function render (movies) {
var moviesDiv = document.getElementById("movies");
moviesDiv.innerHTML = getMoviesHTML(movies);
var numMoviesPara = document.getElementById("numMovies");
numMoviesPara.innerHTML = movies.length + " movies.";
}
render(moviesData);