Corey Roth and Friends Blogs

Group site for developer blogs dealing with (usually) Ionic, .NET, SharePoint, Office 365, Mobile Development, and other Microsoft products, as well as some discussion of general programming related concepts.

Kyle Kelin on .Net

Manipulating the DOM with jQuery

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.

  1. 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.


  2. Adding a new html element

    I also use the appendTo() function to display content dynamically on pages. For example:


        $('#validationSummary').appendTo('<div>invalid data</div>');


  3. Removing content

    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.


  4. 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.




  5. 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.


Published Oct 05 2008, 10:02 PM by KyleKelin
Filed under:


No Comments

Leave a Comment


About KyleKelin

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.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems