When click on prepend first is fine after that repeat multiple

Repeat multiple times?

Any idea why?

https://jsfiddle.net/f6o7h4cz/

Thanks!

It’s because on each click, when you run fun_name() it looks for p tags (all of them) and adds them to the div.
I guess there is a jQuery method called .first()

1 Like

Yup, it’s exactly as @jenovs has said - your code is getting all the paragraph tags present at the moment of the click, and cloning each and every one, and then prepending them. So the first click, it’s getting that first p, and cloning it, and prepending it into div1. The second click, it gets all p elements (there are now two), and clones them, and prepends them before any other content in that div1. The third click, our four paragraphs are seen and cloned, becoming eight. And so on and so forth.

If you only want the first paragraph cloned, then yes, either store that paragraph to a variable before your function is run, and simply clone that paragraph from the variable each time (or use the first() selector each time):

// outside your fun_name(), somewhere global
const myPara = $("p").first();
// or, if you were to do this without jQuery, 
const myPara = document.querySelector("p); // querySelector only returns the first one found

// then, inside your function:
const fun_name = function(eventObj){
  myPara.clone().prependTo(/* your div el here */);
  // No matter how many times I run this, myPara only contains that one element.
};
1 Like