Set innerText using jQuery

In this post, I will explain you that how to set innerText using jQuery. But do you know what is innerText? innerText term means text which appears between the start tag and end tag. In JavaScript, the "inner" text of an HTML element refers to the text between any set of HTML tags and using innerText property, one can set the text in JavaScript.

But to set innerText using jQuery, use text() method. jQuery text() method sets the innerText of any element. Well, we can still club the jQuery and JavaScript without any problem and it will work. An example of innerText would be below.
<span>I am innerText of span element</span>
As I mentioned earlier that one can still use JavaScript in jQuery code so that means one can still use innerText in jQuery to set innerText of any element but there is a problem with this property. This property doesn't work with Firefox. It works quite well with IE and Chrome. So the similar property for Firefox is textContent. But textContent doesn't work with other browsers like IE and Chrome.

As we know that one of the advantage of jQuery is browser independence. So the text() method works in all the browsers. So it works like the textContent property in Firefox and innerText in IE.

Using text() function, you can not only set the text but you can also get the text of element. For example, if you want to set text for any div with id "dvElement" then use following code.
$(document).ready(function()
{
    $("#dvExample").text('I am new content of the div.')
});
And to get the text of the div,
$(document).ready(function()
{
    $("#dvExample").text('I am new content of the div.')
    var dvText = $("#dvExample").text();
    alert(dvText);          
});
Output:



Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..