简体   繁体   中英

How can i make my new bullet points display a string?

First time posting, sorry if i do something wrong.

When i try to make a new list with js, the list elements only display [object HTMLLIElement] in the DOM. I would want it to make a new bullet point which says "Hello" each time i press the button. It only shows this https://gyazo.com/f441c11ce81d80ff14ba4e207c1a7e2d

Here's my code.

 var bodyEl = document.querySelector("body"); var ulist = document.createElement("ul"); var bulletpointEl = document.createElement("li"); bulletpointEl.innerHTML = "hello" bodyEl.appendChild(ulist); function bulletpoint() { ulist.innerHTML += bulletpointEl; } 
 <button onclick="bulletpoint()">New bulletpoint</button> 

You have to use appendChild instead of innerHTML . To create new li element in each button click, you have to create that inside the function.

I will also suggest you to use textContent instead of innerHTML when the content is simple text.

 var bodyEl = document.querySelector("body"); var ulist = document.createElement("ul"); function bulletpoint(){ var bulletpointEl = document.createElement("li"); bulletpointEl.textContent = "hello" ulist.appendChild(bulletpointEl); bodyEl.appendChild(ulist); } 
 <button onclick="bulletpoint()">New bulletpoint</button> <a href="../index.html">back</a> 

The problem is that you're trying to give innerHTML an object instead of a string. innerHTML accepts a string - https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Syntax

If you want to append an html element to the ulist you'll need to use the .appendChild() method same as you did with the bodyEl -

function bulletpoint(){
  ulist.appendChild(bulletpointEl);
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM