Love beautiful code? We do too.
.contents(): Lấy phần tử con của mỗi thành phần trong tập hợp các phần tử phù hợp, bao gồm cả nốt văn bản (text nodes) và nốt bình luận (comment nodes), node có thể hiểu như sau: Theo DOM, tất cả mọi thứ trong tài liệu XML là một node.
.contents() có thể sử dụng để lấy hoặc điều khiển nội dung iframe, nếu iframe có cùng domain với trang sử dụng .content().
Đã được thêm vào từ phiên bản 1.2
.contents()
$('.test').contents();
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('.test').contents().filter('p').css('color','red');
});
</script>
</head>
<body>
<div class="test">
<p>Thành phần p</p>
<span>Thành phần span</span>
</div>
</body>
</html>
Hiển thị trình duyệt:
Với cách sử dụng trên ta đã lọc ra được nội dung của thành phần p nằm trong div có class="test".
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('.test').contents().filter(function() {
return this.nodeType == 3;
})
.wrap('<p></p>')
.end()
.filter('br')
.remove();
});
</script>
</head>
<body>
<div class="test">
Đây là đoạn text đầu.<br /> Đây là đoạn text thứ 2.<br /> Đây là đoạn text cuối.
</div>
</body>
</html>
Hiển thị trình duyệt:
Đoạn code trên sẽ bao (wrap) các đoạn text lại bằng thẻ p, và loại bỏ (remove) các thẻ
.
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#test').contents().find('a').css('color','yellow');
});
</script>
</head>
<body>
<iframe src="http://hoclaptrinh.vn" width="98%" height="150" id="test"></iframe>
</body>
</html>
Kết quả:
Hoclaptrinh.vn © 2017
From Coder With
Unpublished comment
Viết câu trả lời