简体   繁体   中英

Getting value as undefined in Javascript

I'm trying to manipulate value of a button in JS from HTML.

HTML Code:

<div onclick= "classToggle()" type="button" id="show-more">Show more</div>

The output I'm getting for elem is undefined.

JS Code:

function classToggle() {
    var elem = document.getElementById('show-more').value;
    alert(elem);
    if (elem.value == "Show more") elem.value = "Show less";
    else elem.value = "Show more"; }

You are trying to get the value of a div which is not possible. In order to get the text in it, you should be using innerHTML as follows:

 function classToggle() { var elem = document.getElementById('show-more'); alert(elem.innerHTML); if (elem.innerHTML == "Show more") elem.innerHTML = "Show less"; else elem.innerHTML = "Show more"; }
 <div onclick= "classToggle()" type="button" id="show-more">Show more</div>

Use innerHTML instead of value

 function classToggle() { var elem = document.getElementById('show-more'); alert(elem.innerHTML); if (elem.innerHTML == "Show more") elem.innerHTML= "Show less"; else elem.innerHTML = "Show more"; }
 <div onclick= "classToggle()" type="button" id="show-more">Show more</div>

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