Home > Net >  How to add specfic elements to to HTML containers using DOM
How to add specfic elements to to HTML containers using DOM

Time:06-14

I'm doing the Odin Project and am stuck on an exercise.

The requirement is that I have to add specific elements to a container in the HTML file but I can't get the following sections to show up at all when I run it:

a <div> with a black border and pink background color with the following elements inside of it:

another <h1> that says “I’m in a div” a <p> that says “ME TOO!”

Hint for this one: after creating the <div> with createElement, append the <h1> and <p> to it before adding it to the container.

Here's my code https://codepen.io/mohd057/pen/KKQWdYV

const container = document.querySelector('#container');

const myP = document.createElement("p");
myP.style.color = "red"; 
myP.textContent = "Hey I'm red!"; 

const myH = document.createElement("h3")
myH.style.color = "blue"; 
myH.textContent = "I'm a blue h3!"; 

container.appendChild(myP);

container.appendChild(myH);

const myDiv = document.createElement("div"); 
myDiv.setAttribute('style', 'border: black; background: pink;'); 

    const anotherH = document.createElement("h1"); 
    anotherH.textContent = "I'm in a div"; 
    const anotherP = document.createElement("p"); 
    anotherP.textContent = "ME TOO!"; 

    container.appendChild(myDiv);

Here's the link to the exercise https://www.theodinproject.com/lessons/foundations-dom-manipulation-and-events (struggling on questions 3, 1, and 2 are fine)

Would love to know where I'm going wrong.

CodePudding user response:

What is missing:

  • border needs a border-style property to show
  • background's color property is called background-color otherwise you have to define it like this
  • You didn't append any element inside myDiv
const container = document.querySelector('#container');

const myP = document.createElement("p");
myP.style.color = "red"; 
myP.textContent = "Hey I'm red!"; 

const myH = document.createElement("h3")
myH.style.color = "blue"; 
myH.textContent = "I'm a blue h3!"; 

container.appendChild(myP);

container.appendChild(myH);

const myDiv = document.createElement("div"); 
myDiv.setAttribute('style', 'border: black solid; background-color: pink;'); 

    const anotherH = document.createElement("h1"); 
    anotherH.textContent = "I'm in a div"; 
    const anotherP = document.createElement("p"); 
    anotherP.textContent = "ME TOO!"; 

    myDiv.appendChild(anotherH);
    myDiv.appendChild(anotherP);
    container.appendChild(myDiv);
  • Related