Hướng dẫn append html javascript

  • Trang chủ
  • Tham khảo
  • jQuery
  • jQuery – function
  • .append()

Định nghĩa và sử
dụng

  • .append() Chèn nội dung, di chuyển thành phần vào trong thành phần khác, nội dung này thường được sắp xếp ở vị trí sau cùng.

Cấu trúc

  • Đã được thêm vào từ phiên bản 1.0

.append(nội dung)

$('div')

.append('<p>nội dung thêm vào</p>')

; $('div')

.append($('h3'))

;
  • Đã được thêm vào từ phiên bản 1.4

.append(nội
dung)

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    $('div')

.append('<p>nội dung thêm vào</p>')

; }); </script> </head> <body> <div>Thành phần div</div> </body> </html>

Hiển thị trình duyệt:

Ban đầu nội dung chỉ có thành phần div, nhưng khi sử dụng append thì thành phần div được chèn thêm thành phần <p>nội dung thêm vào</p> vào ngay vị trí sau cùng của thành phần div.

So sánh code HTML trước và sau khi có jQuery:

Trước khi có jQuerySau khi có jQuery

<div>Thành phần div</div>

<div>Thành phần div
<p>nội dung thêm vào</p>
</div>

Ví dụ thêm

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    $('div')

.append($('h3'))

; }); </script> </head> <body> <div> <h3>thành phần h3</h3> <p>thành phần p</p> </div> </body> </html>

Hiển thị trình duyệt:

Ban đầu thành phần h3 nằm trong thành phần div ở vị trí đầu, nhưng khi sử dụng append thì thành phần h3 được di chuyển ngay vị trí sau cùng của thành phần div.

So sánh code HTML trước và sau khi có jQuery:

Trước khi có jQuerySau khi có jQuery

<div>
<h3>thành phần h3</h3>
<p>thành phần p</p>
</div>

<div>
<p>thành phần p</p>
<h3>thành phần h3</h3>
</div>

.append(function(index){…})

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    $('div')

.append(function() { return '<p>' + this.className + '</p>'; })

; }); </script> </head> <body> <div class="test01">thành phần div 01</div> <div class="test02">thành phần div 02</div> </body> </html>

Hiển thị trình duyệt:

Với cách sử dụng function như trên, ta đã thêm bên trong mỗi thành phần div lần lượt là thành phần p với nội dung được lấy từ tên class của thành phần div, các thành phần p này nằm ở vị trí sau cùng trong thành phần div tương ứng.

So sánh code HTML trước và sau khi có jQuery:

Trước khi có jQuerySau khi có jQuery

<div class=”test01″>thành phần div 01</div>
<div class=”test02″>thành phần div 02</div>

<div class=”test01″>thành phần div 01
<p>test01</p>
</div>
<div class=”test02″>thành phần div 02
<p>test02</p>
</div>

For example,

var newElement = document.createElement('div');
newElement.innerHTML = "<p>new content</p><script>alert('Hello World!')</script>";
element.appendChild(newElement);​​​​​​​​​​​​​​​​

Result: “new content” is appended in page but there will be no alert saying Hello World!

I have tried innerHTML, insertAdjacentHTML, append, appendChild methods. But the problem is JS and CSS not loading dynamically.

In jQuery, after() works 👍🏻

$(selector).after("<p>new content</p><script>alert('Hello World!')</script>");

is there any equivalent for pure javascript?

Mr. Polywhirl

36.6k12 gold badges76 silver badges124 bronze badges

asked Apr 11 at 16:27

You can use eval to execute your scripts under string formats. jQuery also uses eval in some parts of DOM manipulation under the hood.

const content = "<p>new content<\/p><script>alert('Hello World!')<\/script>";
const newElement = document.createElement('div');
newElement.innerHTML = content
const scriptRegex = /(?<=<script>)(.*)(?=<\/script>)/g; //get scripts between script tags

const scripts = content.match(scriptRegex);
for(const script of scripts) {
  eval(script) //execute your string as a script
}

document.getElementById("content").appendChild(newElement);
<div id="content"></div>

Side note, for your case, there is no way called safety to
convert strings to scripts because somebody may inject malicious scripts into your strings and execute them without your notice, so you need to make sure all your strings are under your control properly. You can check XSS attack for a better understanding.

answered Apr 11 at 16:53

Nick VuNick
Vu

11.9k2 gold badges17 silver badges27 bronze badges

0

If your are sure about HTML string content is safety and contains a string with valid HTML you can use Range.createContextualFragment() (executes scripts 🚨)

const HTMLContent = "<p>new content</p><script>alert('Hello World!')</script>";
const newElement = document.createRange().createContextualFragment(HTMLContent);
document.body.appendChild(newElement)

Working example

answered Apr 16 at 22:05

lissettdmlissettdm

10.9k1 gold badge12 silver badges35 bronze
badges

You have to call your alert when something happens, if you want the alert to be displayed when you append the HTML, then wrap it in a self executing function:

<script>
    (function(){
      alert('Hello World!');
    })()
</script>

answered Apr 11 at 16:32

2

Scripts cannot be added directly to the DOM as HTML text and executed. I would separate the action into two phases. Insert the HTML and add the script to the end of the document body as a contextual fragment.

const insertHTML = (domHTML, scriptHTML, target = document.body) => {
  const el = document.createElement('div');
  el.innerHTML = domHTML;
  document.body.appendChild(el);
  document.body.append(document.createRange().createContextualFragment(scriptHTML));
};

const domHTML = `<p>new content<\/p>`;

const scriptHTML = `
  <script type="text/javascript">
    alert('Hello World!');
  <\/script>
`;

insertHTML(domHTML, scriptHTML);

This logic was
borrowed from Tilak Maddy’s response in a related question.

answered Apr 11 at 16:51

Mr. PolywhirlMr. Polywhirl

36.6k12 gold badges76 silver badges124 bronze badges

If you want to append a script or a stylesheet dynamically into your page, you should:

  1. create a script/link/style tag
  2. edit the tags innerText/innerHTML
  3. append the tag to your page’s head element

Here’s an example to append a script:

var script = document.createElement('script');
    script.src = 'some url'; // use this for external scripts
    script.innerHTML = 'your script'; // use this for writing your own script content

document.getElementsByTagName('head')[0].appendChild(script);

marc_s

714k171 gold badges1315 silver badges1433 bronze badges

answered Apr 11 at 16:49