Creating HTML With JavaScript
Creating HTML With JavaScript
The following HTML has been provided to us, and our task is to recreate
the given card element using JavaScript.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Creating HTML Element with JS</title>
<style>
#parent-container {
display: flex;
flex-direction: row;
}
.card-container {
width: 30%;
display: flex;
flex-direction: column;
text-align: center;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
margin: 10px;
padding-bottom: 5px;
}
<body>
<div id="parent-container">
<div class="card-container">
<img class="image"
src="https://wttc.org/DesktopModules/MVC/NewsArticleList/images/141_2
0201013185512_Consumer%20Survey%20Finds%2070%20Percent%20of
%20Travelers%20plan%20to%20Holiday%20in%202021.jpg" alt="travel-
card" />
<span>The journey of a thousand miles begins with a single
step</span>
</div>
</div>
<script src="index3.js"></script>
</body>
</html>
Output:
Rendered HTML
To re-create the card, we would first fetch the parent-container, by using
document.getElementById(), then we would use the
document.createElement method to create a new element and set the
CSS classes for that element using the .classlist.add() method.
Then, we would create another element - the image element with correct
alt text(using setAttribute) and the span with the text, and finally add
child elements to parent elements using the .appendChild() method.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Creating HTML Element with JS</title>
<style>
#parent-container {
display: flex;
flex-direction: row;
}
.card-container {
width: 30%;
display: flex;
flex-direction: column;
text-align: center;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
margin: 10px;
padding-bottom: 5px;
}
<body>
<div id="parent-container">
<div class="card-container">
<img
src="https://wttc.org/DesktopModules/MVC/NewsArticleList/images/141_2
0201013185512_Consumer%20Survey%20Finds%2070%20Percent%20of
%20Travelers%20plan%20to%20Holiday%20in%202021.jpg" alt="travel-
card" />
<span>The journey of a thousand miles begins with a single
step</span>
</div>
</div>
<script type="text/javascript">
const parentContainer = document.getElementById("parent-
container");
cardContainer.appendChild(cardImage);
cardContainer.appendChild(cardSpan);
parentContainer.appendChild(cardContainer);
</script>
</body>
</html>
Output:
New element made with JS identical to the one made with HTML
Mark as Read
Report An IssueIf you are facing any issue on this page. Please let us know.