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
Well you set result to the li object, you have to get the text inside
result.innerHTML = randomItem.textContent;
If you just want the value you need to access the innerHTML of the <li>.
result.innerHTML = randomItem.innerHTML;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With