-1

I am working on a javascript project, and I am having trouble displaying an appended string. Right now, I am trying to change Crawler1 and Crawler2 to username that a user input. These usernames are stored in local storage:

This is the JS script I am using in order to change the p1 and p2 values to the user names. I am very confused why nothing is appending, because when I use a window.alert box, localStorage.getItem("name") and localStorage.getItem("name2") print the expected values.

document.forms["game"]["p1"].innerHTML = localStorage.getItem("name");
document.forms["game"]["p2"].innerHTML = localStorage.getItem("name2");
<div id="wrap">
  <div id="left_col">
    <p id="p1">Crawler 1</p>    
  </div>

  <div id="right_col">
    <p id="p2">Crawler 2</p>
  </div>
</div>

does anyone have any idea why the p1 and p2 values wouldn't be changing?

0

2 Answers 2

0

did you try using...

document.querySelector('#left_col p').innerHTML = localStorage.getItem("name");
document.querySelector('#right_col p').innerHTML = localStorage.getItem("name");

...?

Or if you really need to scope the query inside the form

const form = document.querySelector('form[name=game]');
form.querySelector('#left_col p').innerHTML = localStorage.getItem("name");
form.querySelector('#right_col p').innerHTML = localStorage.getItem("name");

[edit] Explanation

Looking your markup, you want to access to a <p> inside a <div id="">. document.querySelector() allows you to get a DOMElement using a CSS selector.

The css selector #left_col p matches all the <p> inside an element with id="left_col".

More on CSS Selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Sign up to request clarification or add additional context in comments.

2 Comments

I haven't, what exactly does this do?
This worked!! thank you.. can you please explain why I needed to do this??
0

Forms returns an HTMLCollection of HTMLFormElements

You can access the collection with the id of the names and this will return a HTMLFormElement. But using ['element-id'] on the HTMLFormElement won't do anything.

Instead you can use querySelector as @simnutoli has shown or getElementById like below.

localStorage.setItem('a', 'b');
document.getElementById("p2").innerHTML = localStorage.getItem('a');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.