I want to ask a user for both name and a question with a prompt() method, but when I try to add 2 prompt() methods, one for name and the other for the question, I get this error: Cannot set properties of null (setting 'innerHTML') when trying to output that.
But if I remove the username prompt(), the code work perfectly
const userName = prompt("What is your name?", "Victor");
let userQuestion = prompt("Enter a question", "Can I sleep with my Boss?");
userName.length > 1 ? document.getElementById("8ball").innerHTML = "Hello " + userName + "!" : document.getElementById("8ball").innerHTML = "Hello!";
document.getElementById("ballQ").innerHTML = userName + " " + userQuestion;
<div id="8ball"><p id="ballQ"></p>
<div id="8BallResult"></div>
</div>
Two problems:
The line with the ternary overwrites the innerHTML of #8ball. That removes #ballQ and #8BallResult from the DOM, because they are children of that node; later you get an error when you try to write to #ballQ which no longer exists.
prompt doesn't always return a string; if there's no user input it returns null, and trying to check the .length of null will throw an error.
Below I rearranged your HTML to prevent wiping out DOM nodes you're trying to keep, and changed the .length check against userName to be a simple truthiness check (since all you're really looking for is whether the name exists).
I also rearranged things to make the code easier to read -- all those repeated document.getElementById calls were kind of obscuring what you were trying to do.
let userName = prompt("What is your name?", "Victor");
let userQuestion = prompt("Enter a question", "Can I sleep with my Boss?");
let nodeOne = document.getElementById("8ball");
let nodeTwo = document.getElementById("ballQ");
nodeOne.innerHTML = (userName) ?
"Hello " + userName + "!" :
"Hello!";
nodeTwo.innerHTML = userName + " " + userQuestion;
<div id="8ball"></div>
<p id="ballQ"></p>
<div id="8BallResult"></div>
TypeError: document.getElementById(...) is null
When setting the innerHTML of an element, that does not exist, it'll return null.
You're basically setting a property of null, which is giving you the error.
Make sure that your code comes after the selected element.
Try the following code.
<div id="8ball">
<p id="ballU"></p>
<p id="ballQ"></p>
<div id="8BallResult"></div>
</div>
const userEl = document.getElementById("ballU");
const questionEl = document.getElementById("ballQ");
const userName = prompt("What is your name?", "Victor");
const userQuestion = prompt("Enter a question", "Can I sleep with my Boss?");
userEl.innerHTML = userName ? Hello ${userName}!: Hello!;
if (userQuestion) questionEl.innerHTML = ${userName} ${userQuestion};