Similar to how jQuery, allows us to read and write to a form element, jQuery can allow us to change the contents of an HTML element.
However, instead of using the val() method, jQuery provides two different methods, depending upon what you are wanting/needing to do.
As with the val() method, it is most common applied in response to some event that occurs on the client side. Therefore it is most often found within an event handler.
The .text() Method
As with the val() method, if you do not pass a value to the method, it will return the contents. Where if a value is passed as a parameter, then it will set the contents. But there are certain limitations. The .text() method allows you to get/set the contents, but unmarked text only.
The process will return, or set, the plain text as shown in the following examples.
// get the plain text of the sidebar, and put it into the variable var sideBarText = $('#sidebar').text(); // assign the text into the element $('#content').text(differentText); // pull content from one element, and put it into another $('#content .element1').text($('#content .element2').text());
The .html() Method
The .html() method is very similar to the .text() method. However, it comes with the HTML markup that is contained within the element. This includes, not only tags, but their attributes for classes and ids, so that CSS styles can be applied to the text if right.
This means you can display, and capture html markup. This makes its use slower than the .text(), however, it is more flexible.
Because it is slower, it is suggested, if you know in advance, to use text() if no markup is needed, and .html() if you will have content with markup tags.
// get the plain text of the sidebar, and put it into the variable var sideBarHTML = $('#sidebar').html(); // assign the html content into the element $('#content').html(differentHTML); // pull content from one element, and put it into another $('#content .element1').html($('#content .element2').html());
Mix and Match
Attempts to “mix & match” will not be successful. Essentially, it you put plain text into an html() method, then it will be only have text to display. If you place HTML text into text, then it shows as plain text.
Changing the Content of an HTML Element was originally found on Access 2 Learn