In previous posts I talked about selecting DOM elements with jQuery. In this post I am going to discuss 5 ways you can manipulate the DOM with jQuery.
Setting the contents of an element
There are many situations where you want to add content dynamically to your page (eg. Error messages, ajax results). There are two ways to do this with jQuery, the first being the text(content) function. The syntax for this is pretty straightforward. The code below sets the text of the div with an id of someDiv.
$('#someDiv').text("the content we want to add");
The second way is the html(text) function . The difference between the html and text functions is the text is just the text of the elements and the html is the tags and the text.
Adding a new html element
I also use the appendTo() function to display content dynamically on pages. For example:
One thing I like about jQuery is that the API is very obvious so to remove elements we call the remove() function. Take the following example:
The above statement removes all elements inside the div with the id of validationSummary.
Setting css properties
Another common scenario in web development is dynamically change the look and feel of html using css properties. jQuery makes this super easy with the css() function. The following code will set the text of the div to red. This can be placed in some type of event handler.
Iterating over the matched set
Most jQuery functions work against the first element in the matched set. If you want to manipulate all elements in a matched text you must iterate over the matched set using the each() method.
The example adds a class called clickableImage to every image on our page. In that css class we could set the border to 0.
Kyle Kelin has been implementing software in the Microsoft space for the past 6 years mainly as a consultant. His interests are SharePoint, .NET, JQuery, and Silverlight.