Manipulating DOM Elements Using jQuery and Visual Studio | WebReference

Manipulating DOM Elements Using jQuery and Visual Studio

By Joydip Kanjilal


JQuery is a widely popular open source, cross-browser, CSS3-compliant JavaScript library, which you can use to simplify the tasks involved with writing JavaScript code. One of the main benefits of the jQuery library is that it offers an easy way to manipulate DOM elements in your Web page; you can easily add, edit or delete DOM elements in your HTML content. This article explains how you can manipulate DOM elements in your Web page with jQuery using Visual Studio. Code examples are provided for reference.

To get started with jQuery on Visual Studio, you should have the following installed in your system:

  1. Visual Studio 2008
  2. Visual Studio 2008 SP1
  3. The jQuery Library (Download the latest version from The jQuery Project page.)
  4. Visual Studio 2008 jQuery Plugin

Alternatively, you can simply download and use Visual Studio 2010, as it comes with in-built support for jQuery. If you have Visual Studio 2010, you have the jQuery library by default.

Before we delve deep into the details of using jQuery to manipulate DOM elements in a Web page, let's take a quick tour of jQuery and its benefits.

What Is jQuery? Why Is It Useful?

JQuery provides a common browser API that provides cross-browser support, and using it drastically reduces the amount of code you need to write. The most striking features of jQuery include:

  • Support for browser independence: jQuery is supported by most modern browsers.
  • Support for a simplified event-handling model: jQuery provides support for an excellent, easy-to-use normalized event-handling model with greatly reduced code. The jQuery event-handling model is consistent across all browsers. The event object is cross browser and normalized, and one event object is always passed as a parameter to an event handler.
  • Support for seamless extensibility: jQuery provides support for extensibility through an easy-to-use plugin API that enables extending the jQuery core library seamlessly.

Manipulating DOM Elements

In jQuery, it is quite easy to change the look and feel of a DOM element by adding CSS classes. CSS classes are always preferred in situations where you want to apply element styles that are reusable and can change over time.

To add a CSS class to a DOM element in jQuery, use the following code:

To remove a CSS class attached to a DOM element in jQuery, use the following code:

You can also check to see if a particular CSS class is bound to a DOM element. To do this, you can use the following snippet of code:

You can use the length property to check whether an element exists. Here's an example:

Here is a much simpler version of the code snippet shown above: