Phương thức insertAdjacentHTML beforebegin trong JavaScript
Phương thức insertAdjacentHTML beforebegin trong JavaScript
Phương thức insertAdjacentHTML beforebegin trong JavaScript
Tự code rồi chạy thử...
Chạy Thử
<!DOCTYPE html>
<html>
<head>
<title>Phương thức insertAdjacentHTML beforebegin trong JavaScript</title>
</head>
<body>
<h1>Phương thức insertAdjacentHTML beforebegin trong JavaScript</h1>
<p>Chèn chuỗi HTML vào trước một phần tử HTML, ở ví dụ này mình thêm thẻ p trước thẻ pre, thẻ p chứa chữ copy để copy nội dung thẻ pre:</p>
<div id="divid">
<pre><code>insertAdjacentHTML beforebegin</code></pre>
<pre><code>insertAdjacentHTML beforebegin</code></pre>
<pre><code>insertAdjacentHTML beforebegin</code></pre>
<pre><code>insertAdjacentHTML beforebegin</code></pre>
</div>
<script>
// Lấy nút phần tử id divid
const divid = document.getElementById('divid');
if(divid){
// Lấy danh sách phần tử HTML pre trong phần tử id divid
const pres = divid.getElementsByTagName('pre');
// Lặp qua từng phần tử HTML pre trong phần tử id divid
for (let i = 0; i < pres.length; i++) {
// Tạo phần tử HTML p
const noiDungHtml = "<p>Copy</p>";
// Lấy thẻ pre cần thêm
const prett = divid.getElementsByTagName("pre")[i];
if(prett){
// Thêm thẻ p vào phía trước thẻ pre
prett.insertAdjacentHTML('beforebegin', noiDungHtml);
}
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Phương thức insertAdjacentHTML beforebegin trong JavaScript</title>
</head>
<body>
<h1>Phương thức insertAdjacentHTML beforebegin trong JavaScript</h1>
<p>Chèn chuỗi HTML vào trước một phần tử HTML, ở ví dụ này mình thêm thẻ p trước thẻ pre, thẻ p chứa chữ copy để copy nội dung thẻ pre:</p>
<div id="divid">
<pre><code>insertAdjacentHTML beforebegin</code></pre>
<pre><code>insertAdjacentHTML beforebegin</code></pre>
<pre><code>insertAdjacentHTML beforebegin</code></pre>
<pre><code>insertAdjacentHTML beforebegin</code></pre>
</div>
<script>
// Lấy nút phần tử id divid
const divid = document.getElementById('divid');
if(divid){
// Lấy danh sách phần tử HTML pre trong phần tử id divid
const pres = divid.getElementsByTagName('pre');
// Lặp qua từng phần tử HTML pre trong phần tử id divid
for (let i = 0; i < pres.length; i++) {
// Tạo phần tử HTML p
const noiDungHtml = "<p>Copy</p>";
// Lấy thẻ pre cần thêm
const prett = divid.getElementsByTagName("pre")[i];
if(prett){
// Thêm thẻ p vào phía trước thẻ pre
prett.insertAdjacentHTML('beforebegin', noiDungHtml);
}
}
}
</script>
</body>
</html>
Phương thức insertAdjacentHTML beforebegin trong JavaScript nằm trong bài viết Phương thức insertAdjacentHTML trong JavaScript