Add in Jquery
Great! Lets explore how to use .add() in jQuery both the .add() method and how to add elements or content dynamically to your HTML page.
? 1. jQuery .add() Method
The .add() method is used to combine multiple selectors into one jQuery object so you can work with all selected elements together.
? Syntax:
$(selector1).<p "#highlightBtn").click(function() { $(".one").add(".two").css("color", "red"); });</script>
? This will apply the same CSS to both .one and .two.
? 2. Adding Content with jQuery
You can also add elements or content dynamically using:
? .append() Adds content inside the end of an element
? .prepend() Adds content inside the beginning
? .after() Adds content after the element
? .before() Adds content before the element
? Example 1: .append()
"#addText").click(function() { $("#box").append(" World!"); });</script>
? Example 2: .after() with a new element
"#addPara").click(function() { $(this).after("<p>This is a new paragraph.</p>"); });</script>
? Quick Comparison
| Method | Adds Content... |
|---|---|
.append() | Inside the element (end) |
.prepend() | Inside the element (start) |
.after() | After the element |
.before() | Before the element |