Hello I have a simple javascript function that chooses a random list item in an unordered list with the press of a button. It works fine, the console spits out a random list item when the button is clicked but when I try to display it on the HTML page all I am getting is this weird [object HTMLLIElement] instead of the text.
The goal is to display the text inbetween the list item. When I click the button it chooses a random list item for example: <li>5</li>
but I would like for just the 5
to be displayed.
Here is the HTML:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
<button id="randomize">randomize</button>
<p id="result">hello</p>
and the JS:
var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");
randomize.addEventListener("click", randomizeIt);
function randomizeIt () {
var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
result.innerHTML = randomItem;
console.log(randomItem);
}
thanks in advance
好吧,您将结果设置为li
对象,您必须将文本放入其中
result.innerHTML = randomItem.textContent;
如果只需要该值,则需要访问<li>
的innerHTML。
result.innerHTML = randomItem.innerHTML;
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.