How to click on a paragraph and add another paragraph using jQuery ?
In this article, we will learn how to add another paragraph to the document when a paragraph is clicked using jQuery.
Approach: We will be using the delegate() and after() methods of jQuery. The delegate() method is used to add event listeners to the given element. This will be used to add a click event listener to the paragraph element. This method takes three parameters, in our case, the child-selector is the paragraph element, the event is “click” and the function is an anonymous function.
The anonymous callback function is used to add a new paragraph to the document. This is done using the after() method that inserts the given element after the selected element in the document. We will insert a new paragraph element after the current one by using the this binding as the selector. This will hence add a paragraph element to the document after the one that was clicked. We can also add a counter variable to see this in effect.
Syntax:
$(selector).delegate("target_elem", function() {
$(this).after("content");
})
The below example demonstrates this approach.
Example:
HTML
< html >
< head >
< style >
p {
background: green;
color: white;
padding: 5px;
}
</ style >
< script src =
</ script >
</ head >
< body style = "text-align: center;" >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< p >
Click on the paragraphs to start
adding new paragraphs
</ p >
< script >
// A count variable to keep track
// of the current paragraph
let cnt = 0;
// Add the click event listener to
// the required paragraph element
$("body").delegate("p", "click",
function() {
// Insert a new paragraph after
// this paragraph
$(this).after(
"< p >New paragraph " +
cnt + "</ p >
");
cnt++;
});
</ script >
</ body >
</ html >
|
Output:
Last Updated :
31 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...