Home > Web Front-end > JS Tutorial > How to Insert Script Tags into HTML Documents Using JavaScript?

How to Insert Script Tags into HTML Documents Using JavaScript?

Linda Hamilton
Release: 2024-10-21 06:32:02
Original
702 people have browsed it

How to Insert Script Tags into HTML Documents Using JavaScript?

Inserting Script Tags into HTML Documents in JavaScript

To dynamically add script tags to your HTML document, you can leverage the appendChild() method or jQuery's append(). However, directly appending script tags may result in the content being stripped out.

Using document.createElement()

To overcome this issue, you can create the script tag using document.createElement(), and then manually set the HTML content using script.innerHTML. Finally, append the script element to the head or body of the document:

// Create the element

var script = document.createElement("script");

// Add script content

script.innerHTML = "...";

// Append

document.head.appendChild(script);
Copy after login

Alternatively, you can append to the body:

document.body.appendChild(script);
Copy after login

Using jQuery

If you're using jQuery, you can append the script element using the append() method:

// Create the element

var script = $("<script>").html("...");

// Append

$("head").append(script);
Copy after login

This method simplifies the process by automatically creating the script tag and handling the content insertion.

The above is the detailed content of How to Insert Script Tags into HTML Documents Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Previous article:Libraries You Should Know When Building with React Next article:How to Append
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template