javascript - How do I change the displayed text within a button using pure js? -
i'm beginner coding , wondering if guys might help.
i've seen lot of stuff online using innerhtml
, textcontent
, value
etc. change displayed text tag can't change on-screen.
note: console.log
's fire , display expected text in console correct content button content doesn't change in window.
here's html:
<h1 id="myheading" class="red">javascript , dom</h1> <p>making web page interactive</p> <button id="mybutton">click me</button>
here's javascript:
const myheading = document.getelementbyid('myheading'); const mybutton = document.getelementbyid('mybutton'); let buttontext = mybutton.innertext; console.log(buttontext); mybutton.addeventlistener('click', function togglecolor() { let whatclass = myheading.classlist; if (whatclass.contains('red')) { whatclass.remove('red'); whatclass.add('yellow'); buttontext = 'click me change text red!'; console.log(buttontext); } else if (whatclass.contains('yellow')) { whatclass.remove('yellow'); whatclass.add('red'); buttontext = 'click me change text yellow!'; console.log(buttontext); } });
thanks in advance , please don't harsh!
use mybutton.innertext
or mybutton.innerhtml
const myheading = document.getelementbyid('myheading'); const mybutton = document.getelementbyid('mybutton'); let buttontext = mybutton.innertext; //console.log(buttontext); mybutton.addeventlistener('click', function togglecolor() { let whatclass = myheading.classlist; if(whatclass.contains('red')) { whatclass.remove('red'); whatclass.add('yellow'); mybutton.innertext = 'click me change text red!'; } else if(whatclass.contains('yellow')) { whatclass.remove('yellow'); whatclass.add('red'); mybutton.innerhtml = 'click me change text yellow!'; } });
.red{background:red} .yellow{background:yellow}
<h1 id="myheading" class="red">javascript , dom</h1> <p>making web page interactive</p> <button id="mybutton">click me</button>
Comments
Post a Comment