Reputation: 185
I want to use javascript to create the following div block:
<div class=id="hello">
<h1 class="header-1"></h1>
<img>
<p class="paragraph-1"></p>
</div>
I have another javascript object, which holds the url for the image. It is an object with {url}. So I would like to have a function which creates the HTML code above with nesting, but also lets me assign the img src as the url of the object I have. Do I just create a function with a return block like this:
{<div class=id="hello">
<h1 class="header-1"></h1>
<img>
<p class="paragraph-1"></p>
</div>}
?
Upvotes: 0
Views: 803
Reputation: 11451
As @Cid mentioned in the comments, using document.createElement()
is a good idea.
<!DOCTYPE html>
<html>
<body>
</body>
<script>
const div = document.createElement("div"); // create a div
const h1 = document.createElement("h1"); // create a h1
const img = document.createElement("img"); // create an image tag
const p = document.createElement("p"); // create a paragraph
div.classList.add("hello"); // assign "hello" css class
div.id = "hi"
h1.classList.add("header-1"); // assign "header" css class
p.classList.add("paragraph-1"); // assign "paragraph-1" css class
div.appendChild(h1); // nest h1 inside div
div.appendChild(img); // nest img inside div
div.appendChild(p); // nest p inside div
document.body.appendChild(div); // add div to current document
</script>
</html>
Upvotes: 2