Inserting Content Outside Elements
In this page:
after()
The after() method inserts new content as a sibling immediately following the selected element, outside of it rather than inside. Unlike append(), the new content becomes a sibling in the parent's child list, not a child of the selected element itself.
Example: after()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="ref">Reference</p>
<script>
$("#ref").after("<p>After content</p>");
</script>
</body>
</html>
before()
before() inserts content immediately before the selected element as a preceding sibling. It's the mirror image of after(), useful when new content needs to appear ahead of an existing element rather than after it.
Example: before()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="ref">Reference</p>
<script>
$("#ref").before("<p>Before content</p>");
</script>
</body>
</html>
Insert Existing Elements
after() and before() can move existing elements to a new position in the DOM, just like append() and prepend() can. Moving an element this way automatically removes it from its previous location.
Example: Insert Existing Elements
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="a"><p id="moveMe">Move me</p></div>
<p id="ref">Reference</p>
<script>
$("#ref").after($("#moveMe"));
</script>
</body>
</html>
Add Messages
These methods are useful for adding notices around existing content, such as inserting a validation error message directly after an invalid input field. Placing the message as a sibling keeps it visually and structurally tied to the element it relates to.
Example: Add Messages
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="email" type="text">
<script>
$("#email").after("<span class='error'>Invalid email</span>");
</script>
</body>
</html>
Position Matters
before() places content before an element in the document order; after() places it immediately following. Because both insert outside the element rather than inside it, they only work on elements that already have a parent to attach the sibling to.
Example: Position Matters
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="ref">Reference</p>
<script>
$("#ref").before("<p>Before</p>").after("<p>After</p>");
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: