Monday, August 22, 2011

Content manipulation with jQuery

Content manipulations mechanisms exist to let you change or update you web page content.
You can change the value of a search box, insert fresh and new html tag to an existing div or even remove certain section from your page dynamically. (and many more, of course)

jQuery provides simple and fast methods for content manipulation. The simplest methods in jQuery are html() and text(). These two serves as setters and getters of content according to the number of params you pass them.

If the call is empty - they serve as getters. For example:

$("#myComponent").html();

Will return all html content inside the element with the id myComponent

$("#myComponent").html('<div>Hello</div>');

Will set the inner html of the element with the id myComponent to be <div>Hello</div>

Simple and Running.

So, what should you use? html() or text() ?

The rule of thumb is that html() returns everything that exist inside the jQuery selector element while text() ignores HTML elements and returns the text only.

html() - is similar to innerHTML property
text() - is similar to the innerText or innerContent properties

Setting content

Setting content has no surprise here, html(content) will set HTML content inside the selected element. This means that if an HTML element will present inside the inserting content, it will be rendered by the browser. text(content) will insert the text "AS IS" to the selected component.

Example:

$("#myComponent").html('<div><i>Hello</i></div>');
$("#myComponent").text('<div><i>Hello</i></div>');

The first line results in the insertion of hello into the selected element (italic hello). The second results in inserting the string "<div><i>Hello</i></div>" (string! no html here!)


Right, Simple and Running.

Enjoy.

No comments:

Post a Comment