This is a paragraph.

Interesting about hide (). After ("") in jQuery

I have the code here :

HTML:

<body> <p>This is a paragraph.</p> <button>click me</button> </body> 

JavaScript:

 $(document).ready(function(){ $("button").click(function(){ $("p").hide().after('<p>hello world</p>'); }); }); 

In fact, I also used JQuery 2.0.2 .


In my understanding, When I click the button I click on me , "<p>This is paragraph<p>" will be replaced by <p>hello world</p> .

The first click is successful. However, many hello world with progression growth rates are shown after the first shown hello world . For example:

hello world


I checked the firebug source code and found:
 <p style="display: none;">This is a paragraph.</p> <p>hello world</p> <p style="display: none;">hello world</p> <p>hello world</p> <button>click me</button> 

Why was the first <p>hello world</p> not replaced by a new one?

Is only one p tag expected?

+7
javascript jquery html jquery-after
source share
5 answers

That means you create paragraphs

<p>hello world</p>

and every click of $('p') is a collection of all p elements on your page.
The more paragraphs you have ... the more adds. live demo

An element, even if it is set to display:none with .hide() , is still present in your document.


What you are doing is probably one of the following:
  $("button").click(function(){ $("p").html('hello world'); }); 

  $("button").click(function(){ $("p").text('hello world'); }); 

  $("button").click(function(){ $("p").replaceWith('<p>hello world</p>'); }); 

  $("button").click(function(){ $("p").after('<p>Hello world</p>').remove(); }); 
+8
source share

If you want to change the text you like,

 $(document).ready(function(){ $("button").click(function(){ $("p").html('hello world'); }); }); 

JS FIDDLE

+1
source share

well ... there is nothing surprising in what happens here ... actaully, this is what should happen ... because you add the <p> after hiding the first <p> <p>This is paragraph<p> .. so that your first click ends with two <p> tags in the tag and subsequent clicks, adding <p> tags. hide() does not remove dom form elements .. it just changes its display property ... you can use replaceWith() or remove() to remove the first <p> if you want this to work as you need

  $("p").after('<p>hello world</p>').remove(); //remove the selected `<p>` tag after `<p>is appended.</p>` 

or

  $("p").replaceWith('<p>hello world</p>'); 
+1
source share

after('<element/>') means to generate an element and insert it after the selected element (s) that you generate and insert the element after all selected p elements, the first time you add 1 element, click 2 on the second element, etc. e., because after each click there are several p elements. after does not replace anything.

+1
source share

This happens because you add a new p element after each p-tag in the document (even after hidden ...)

0
source share

All Articles