jQuery: before() & after() method
Phương thức before() dùng để chèn nội dung vào trước những phần tử được chỉ định, còn phương thức after() dùng để chèn nội dung vào sau những phần tử được chỉ định.
Ví dụ:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis. com/ajax/libs/jquery/1.11.1 /jquery.min.js"></script>
<script>
$(function(){
$("#btn1").click(function(){
$("section").before("<b>Before</b>");
});
$("#btn2").click(function(){
$("section").after("<i>After</i>");
});
});
</script>
</head>
<body>
<section style="color:red; font-weight:bold">v1study.com</section
<br><br>
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
</body>
</html>
Demo:
Thêm phần tử mới bằng after() và before()
Ta cũng có thể sử dụng các phương thức after() và before() để tạo cùng lúc nhiều phần tử mới. Phần tử mới có thể được tạo bằng HTML, jQuery, hoặc JavaScript/DOM.
Ví dụ dưới đây sẽ sử dụng phương thức after() để tạo một số phần tử mới.
Ví dụ:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis. com/ajax/libs/jquery/1.11.1 /jquery.min.js"></script>
<script>
function beforeText(){
var txt1 = "<b>I </b>"; //Tạo phần tử bằng HTML
var txt2 = $("<i></i>").text("love "); //Tạo phần tử bằng jQuery
var txt3 = document.createElement("b"); //Tạo phần tử bằng JavaScript/DOM
txt3.innerHTML = "v1study.com! ";
$("section").before(txt1, txt2, txt3);
}
function afterText(){
var txt1 = "<b>I </b>";
var txt2 = $("<i></i>").text("love ");
var txt3 = document.createElement("b");
txt3.innerHTML = "demo.v1study.com ";
var txt4 = "<em>too! </em>";
$("section").after(txt1, txt2, txt3, txt4);
}
</script>
</head>
<body>
<section style="color:red; font-weight:bold;">v1study.com</section>
<br /><br />
<button onclick="beforeText();">Insert before</button>
<button onclick="afterText();">Insert after</button>
</body>
</html
Demo: