Manipulating DOM Elements Using jQuery and Visual Studio [con't]
Manipulating DOM Elements (cont'd)
You can also set values to CSS properties dynamically. As an example, you might need to add color to the text of an element that displays error messages. To do this, you can use the following code:
You can also use the css()
method in jQuery to retrieve an element's property, as shown in the code snippet below:
To add a new HTML element to the DOM tree, you can use the appendTo()
method in jQuery. The following code snippet shows how you can add content inside the EmployeeSummary
div:
.append()
and .appendTo()
jQuery methods work much the same way; they differ only in syntax and the placement of content. Consider the following HTML content:
Now, you use the .appendTo()
jQuery method and add a paragraph to the div having the name "first", as shown in the code snippet below:
The resultant HTML content now becomes:
You can also set the contents of a DOM element dynamically in jQuery as shown here:
To remove elements contained within a DOM element, you can use the remove()
method in jQuery. As an example, the following piece of code can be used to remove all elements contained inside the div EmployeeSummary
:
You can use the .remove()
method to remove an option from a select list, as shown in the code snippet below:
You can also use the .detach()
jQuery method to remove elements. This method works much the same way as .remove()
except that it preserves the associated jQuery data so that the removed elements can be reinserted later.
To retrieve the option selected as text from a select list, you can use the following snippet of code:
The .closest()
jQuery method can be used to retrieve the immediate parent of a particular DOM element. The following piece of code illustrates how this can be done:
The .siblings()
method in jQuery returns the siblings of a given DOM element. Here's an example:
Summary
The jQuery library is capable of much, much more in JavaScript development. This article just gets you started with manipulating DOM elements in jQuery. Happy coding!
Further Reading
Here are a few links to resources for further study on this topic:
Original: September 20, 2010