What's new? | Help | Directory | Sign in
Google
             
Search
for
Updated Nov 15, 2008 by pilgrim
Labels: is-article, about-dom
ArticleSetTextContent  
HOWTO set the text content of an element (goog.dom.setTextContent)

TODO intro

The code

/**
 * Cross browser function for setting the text content of an element.
 * @param {Element} element The element to change the text content of
 * @param {String} text The string that should replace the current element
 *                      content with.
 */
goog.dom.setTextContent = function(element, text) {
  if ('textContent' in element) {
    element.textContent = text;
  } else if (element.firstChild &&
             element.firstChild.nodeType == goog.dom.NodeType.TEXT) {
    // if the first child is a text node we just change its data and remove the
    // rest of the children
    while (element.lastChild != element.firstChild) {
      element.removeChild(element.lastChild);
    }
    element.firstChild.data = text;
  } else {
    while (element.hasChildNodes()) {
      element.removeChild(element.lastChild);
    }
    var doc = goog.dom.getOwnerDocument(element);
    element.appendChild(doc.createTextNode(text));
  }
};

The code walkthrough

TODO walkthrough

Further reading

TODO further reading


Sign in to add a comment