Exercises DOM Manipulation


#1

Hey guys,

I’m currently working on the exercise in the DOM manipulation section. Here’s my code for the first two tasks:

  • a p with red text that says “Hey I’m red!”

  • an h3 with blue text that says “I’m a blue h3!”

          const cont = document.querySelector('#container');
      
          let redContent = document.createElement('p'); 
          redContent.textContent = "Hey, I'm red!" ; 
          redContent.style.color = 'red'; 
      
         cont.appendChild(redContent);
      
         let blueContent = document.createElement('h1'); 
         blueContent.textContent = "Hey I'm blue!"; 
         blueContent.style.color = 'blue'; 
      
         cont.appendChild(blueContent); 
    

Although the HTML itself works, none of the changes I made in the JS are visible. I’ve tried to reposition the code but it didn’t do much difference. Is there something I’m overlooking?

Many thanks
Xierras


#2

Do you have a div in your HTML code with an id of ‘container’?


#3

Yeah, I copy and pasted the code from one of the examples mentioned earlier in that tutorial.

  <h1>
THE TITLE OF YOUR WEBPAGE
  </h1>
  <div id="container">
  	<div class="content">
  This is the glorious text-content!
</div>
  </div>

#4

Are you importing the javascript file in the head section of your html file?


#5

I’ve put the code between the <script> tags in the HTML file. I tried both, putting it at the bottom in and after the body tag.


#6

If you put it at the bottom of the body tag it should work. Can you share a screenshot of what you see?


#7

That’s the code in VS Code and what I see in the browser


#8

That’s weird. It works for me if you run this


#9

Weird indeed. I just created a new file and copy and pasted it again and it worked!

Thanks anyway, I’m glad I got it running in the end :slight_smile: