Introduction to DOM Manipulation with jQuery:
DOM manipulation is a crucial aspect of web development, allowing developers to dynamically change the structure, style, and content of web pages. jQuery simplifies DOM manipulation by providing easy-to-use methods to modify attributes, styles, and content of DOM elements.
Modifying Attributes with jQuery:
Changing Attribute Values:
jQuery provides methods to change attribute values of DOM elements dynamically. The attr()
method is used to get or set attribute values.
<script>
$(document).ready(function() {
// Set the src attribute of an image
$("img").attr("src", "newimage.jpg");
});
</script>
In this example, the attr()
method sets the src
attribute of all <img>
elements to "newimage.jpg".
Removing Attributes:
jQuery also allows you to remove attributes from DOM elements using the removeAttr()
method.
<script>
$(document).ready(function() {
// Remove the href attribute from all anchor elements
$("a").removeAttr("href");
});
</script>
This jQuery code removes the href
attribute from all <a>
elements.
Modifying Styles with jQuery:
Changing CSS Properties:
jQuery enables you to modify CSS properties of DOM elements using the css()
method.
<script>
$(document).ready(function() {
// Change the background color of all paragraphs
$("p").css("background-color", "yellow");
});
</script>
This jQuery code changes the background color of all <p>
elements to yellow.
Adding and Removing CSS Classes:
You can add or remove CSS classes from DOM elements using the addClass()
and removeClass()
methods.
.highlight {
font-weight: bold;
color: red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Add the 'highlight' class to all <h1> elements
$("h1").addClass("highlight");
// Remove the 'highlight' class from all <p> elements
$("p").removeClass("highlight");
});
</script>
In this example, the addClass()
method adds the "highlight" class to all <h1>
elements, while the removeClass()
method removes the "highlight" class from all <p>
elements.
Modifying Content with jQuery:
Changing Text Content:
jQuery provides methods to modify text content of DOM elements using text()
and html()
methods.
<script>
$(document).ready(function() {
// Change the text content of all <h2> elements
$("h2").text("New Heading");
});
</script>
This jQuery code changes the text content of all <h2>
elements to "New Heading".
Changing HTML Content:
You can also change the HTML content of DOM elements using the html()
method.
<script>
$(document).ready(function() {
// Change the HTML content of all <div> elements
$("div").html("<p>New paragraph</p>");
});
</script>
<div>
elements to <p>New paragraph</p>
. Practice Excercise Practice now