Skip to content

Instantly share code, notes, and snippets.

@seantunwin
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save seantunwin/37872c59998c72e3fd05 to your computer and use it in GitHub Desktop.

Select an option

Save seantunwin/37872c59998c72e3fd05 to your computer and use it in GitHub Desktop.
Function to change the text of a button using textContent with a fallback for old browsers
/* Try it at Codepen.io - http://codepen.io/seantunwin/pen/aDsHE */
/**
* Change the text of a button
* @param {el} object HTMLElement: button to change text of
* @param {dText} string: default text
* @param {nText} string: new text
**/
function changeText(el, dText, nText) {
var content = '',
context = '';
/* Check to see if the browser accepts textContent */
if ('textContent' in document.body) {
context = 'textContent';
/* Get the current button text */
content = el[context];
/* Browser does NOT use textContent */
} else {
/* Get the button text with fallback option */
content = el.firstChild.nodeValue;
}
/* Set button text */
if (context === 'textContent') {
el.textContent = (content === dText) ? nText : dText;
} else {
el.firstChild.nodeValue = (content === dText) ? nText : dText;
}
}
/* Default text of the button */
var defaultText = 'Change';
/* Alternate text for button */
var substituteText = 'Revert';
/* Grab our button */
var btn = document.querySelector('.btn');
/* Add a listener to the button instance so we can manipulate it */
btn.addEventListener('click', function() {
changeText(this, defaultText, substituteText);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment