We can add content to the
section of the website using jQuery's "append" or "prepend" methods. This can be done by selecting the element using jQuery's "selector" method and then adding the required content using the appropriate method. Additionally, we can add content to the section using JavaScript's 'innerHTML' attribute.There are many ways to add content to the head tag programmatically. Today we will discuss 3 of them -
Use jQuery’s .append() method -
Use JavaScript’s document.createElement() method -
Use JavaScript's insertAdjacentHTML() method -
Use these 3 methods to achieve the same task, which is to add content to the
So, let us discuss these methods one by one.
This is a simple one-liner for appending content to any tag in HTML (in our case it will be the head tag) -
$("head").append("alert('hello');");
We can achieve the same functionality as this using the JavaScript createElement() function and then the appendChild() function -
var script = document.createElement("script"); script.innerHTML = "alert('hello');"; document.getElementsByTagName("head")[0].appendChild(script);
The last method we want to discuss is JavaScript’s insertAdjacentHTML() method -
document.head.insertAdjacentHTML("beforeend", "alert('hello');");
Now that we have discussed all these methods separately, let us use them in a working example.
The complete code is as follows -
<html> <head> <title>Content in head section</title> </head> <body> <h1 style = "color: black;">Welcome to my website</h1> <script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script> <script> // Using jQuery's .append() method $("head").append("<link rel='stylesheet' href='styles.css'>"); // Using JavaScript's document.createElement() method var meta = document.createElement("meta"); meta.name = "description"; meta.content = "This is my website"; document.getElementsByTagName("head")[0].appendChild(meta); </script> </body> </html>
The above is the detailed content of How to add content to a section using jQuery/JavaScript?. For more information, please follow other related articles on the PHP Chinese website!