Home > Article > Web Front-end > Introduction to the differences between insertBefore(), insertAfter(), after(), and before() in jQuery
This article mainly introduces the differences between insertBefore(), insertAfter(), after(), and before() in jQuery The information is very good and has reference value. Friends who need it can refer to it
insertBefore():a.insertBefore(b)
a is in the front, b is in the back,
a: is a selector, b: is also a selector
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>jqu</title> <script type="text/javascript" src='jquery-2.2.0.min.js'></script> </head> <body> <p class='p1'>p1:hello</p> hello world <p class='p2'>p2:wenwen</p> hello wo </body> <script type="text/javascript"> $(function(){ $('.p2').insertBefore('.p1'); }) </script> </html>
Get:
p2:wenwen p1:hello hello world hello wo
insertAfter(): It is the same as insertBefore()
a.insertAfter(b)
a is after , b is in front
Now it means before()
before():a.before()
a is on the page There is an existing selector, b is the content you need to add, note: it is what it is, it will recognize the tag, b is not a selector
A comes after, b comes before
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>jqu</title> <script type="text/javascript" src='jquery-2.2.0.min.js'></script> </head> <body> <p class='p1'>p1:hello</p> <p class='p2'>p2:wenwen</p> </body> <script type="text/javascript"> $(function(){ $('.p2').before('.p1'); }) </script> </html>
Finally got:
p1:hello .p1 p2:wenwen
See? .p1 does not recognize the selector, it is directly string, in front of the .p2 selector
after(): It is the same as before(), except One in front and one in back
I just want to say the difference between insertBefore(), insertAfter() and before(), after(). I feel that the biggest difference is to see the scenario you want to use it. , if you need to swap the positions of two selectors, use
insertBefore(), insertAfter()
If you need to swap the positions of a selector and a text, just use You can use before(), after(); of course, this is not just about changing the position.
Changing the position means things that already exist on the page. This method can also add things that are not on the page, such as :
$('<p class='p3'>嘿嘿</p>').insertBefore('.p1');
The above is the detailed content of Introduction to the differences between insertBefore(), insertAfter(), after(), and before() in jQuery. For more information, please follow other related articles on the PHP Chinese website!