Thursday, February 5, 2015

JavaScript: The Difference between innerHTML and innerText

The basic
These methods can do the get or set process.
On Firefox (I was using Chrome), the innerText method doesn't work.
Firefox uses textContent instead. It will work like innerText but a bit different, you can compare the string-only output using Firefox and Chrome.

Internet Explorer supports innerText method by default.

GET
  • The JavaScript innerHTML will capture everything inside the element reference (the parent).
    USAGE
    var inner_html = the_parent_element.innerHTML;
    The inner_html variable will consist of HTML elements inside the_parent_element.
    The jQuery equivalency of innerHTML (get) is $(parent).html()
  • The innerText will capture only the string (plus the escaped HTML tags) inside the element reference. All other will be stripped out.
    USAGE
    var inner_text = the_parent_element.innerText;
    The inner_text variable will consist of text (string) inside the_parent_element.
    The jQuery equivalency of that is $(parent).text()

SET
  • The JavaScript innerHTML can also set the HTML content of the element reference (the parent).
    USAGE
    the_parent_element.innerHTML = "<div>the content</div>";
    The the_parent_element variable will consist of new HTML elements declared above.
    The jQuery equivalency for that is $(parent).html("<div>the content</div>")
  • The innerText will set the string for the element reference.
    USAGE
    the_parent_element.innerText = "the text";
    The the_parent_element variable will have new text (string) inside it.
    The jQuery equivalency for that example is $(parent).text("the text")

Additional remark about innerText for Internet Explorer (and other browser)
msdn.microsoft.com/en-us/library/ie/ms533899(v=vs.85).aspx
The innerText property is valid for block elements only.
By definition, elements that do not have both an opening and closing tags cannot have an innerText property.

Let's see the get process
I'll create an element, let's put the id attribute as the_parent_element with some other elements inside it. As such:

Demo
For get method.
Ho ho ho, I am sumthin.

I hope you get the idea.
You can try the set process yourself on your browser console.
You can destroy this page all you want. Ho ho ho. JK.

No comments:

Post a Comment

Tell me what you think...