Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Aoto Sakamoto
Aoto Sakamoto
1,550 Points

How would I "document.write" the output from the prompt, with a h1 tag, without using script tags?

although writing this would work: <h1> <script> const username = prompt('What is your name?'); document.write(username); </script> </h1>

I wanted to do this without going to the html file, and instead working with it in the js file. Is there a way to do this?

1 Answer

Madushan Perera
Madushan Perera
7,624 Points

You can use a button ** and its onClick event to execute the prompt. After that get the value from the prompt and pass it the **h1 element by selecting it and change the h1 element's innerHTML value.

HTML file -->

<h1 id="#yourh1tag"></h1>
<button id="yourButton">Click me</button>

JavaScript file -->

function myFunction() {
  var person = prompt("Please enter your name");
  if (person != null) {
    document.getElementById("#yourh1tag").innerHTML =
    "Hello " + person + "! How are you today?";
  }
}

const yourButton = document.getElementById("#yourButton")
yourButton .addEventListener('onClick', myFunction);