Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting [object HTMLLIElement] instead of text. Javascript function

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

like image 874
cup_of Avatar asked Apr 07 '26 15:04

cup_of


2 Answers

Well you set result to the li object, you have to get the text inside

result.innerHTML = randomItem.textContent;
like image 194
Musa Avatar answered Apr 09 '26 04:04

Musa


If you just want the value you need to access the innerHTML of the <li>.

result.innerHTML = randomItem.innerHTML;
like image 28
Hadeaz Avatar answered Apr 09 '26 05:04

Hadeaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!