Search code examples
javascripthtmlgoogle-chrometextinnertext

How to set innerText in JavaScript for Chrome?


I am trying to set the innerText between an element's start and end tag in Chrome, but so far its not working. Why is that? I have tried these:

element.balanceText = "Changed.";
element.innerText = "Changed.";
element.innerHTML = "Changed.";
element.textContent = "Changed.";
element.value = "Changed.";
$(element).val("Changed.");

Here is the fiddle: http://jsfiddle.net/La1tadpd/


Solution

  • Your jsFiddle is configured to use Coffee Script not plain JavaScript, and because of this, you're getting an error:

    Uncaught SyntaxError: reserved word "var"

    Due to the input tag being invalid HTML, I suggest removing the additional text node that the browser creates, then replace the input element with a div containing the text you want:

    var element = document.getElementById('test');
    element.nextSibling.parentNode.removeChild(element.nextSibling);
    
    var div = document.createElement('div');
    div.textContent = 'Changed.';
    
    element.parentNode.replaceChild(div, element);
    <input id='test'>Hello</input>