Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perfect

Joshua Bivens
Joshua Bivens
8,586 Points

How do I toggle a button's text when clicked?

I'm trying the "perfect" part of a js todo app project. I want to toggle a button to read "Save" when in an edit mode and "Edit" when not. How?

2 Answers

Sean T. Unwin
Sean T. Unwin
28,660 Points

Use .textContent for modern browsers or .firstChild.nodeValue for IE8 and less.

Of note, using .innerText is not compatible with Firefox so that is why I didn't suggest it even though Andrew Chalkley uses it in the course.

Click to view a functional example on Codepen or see the code below for a light example.

E.g.

if (myBtn.textContent === "Edit") {
  myBtn.textContent = "Save";
} else {
  myBtn.textContent = "Edit"
}

:)

Brian Polonia
Brian Polonia
25,139 Points

I posted an answer to this same question, in reference to the last video of the Interactive Web Pages with JavaScript course.

Here is the link: Click Here

Hope this helps.

  • Brian