How to add content in section using jQuery/JavaScript?

We can use jQuery's 'append' or 'prepend' method to add content to the <head> section of a website. This can be done by selecting the <head> element using jQuery's 'selector' method and then using the appropriate method to add the desired content. Additionally, we can also use JavaScript's 'innerHTML' property to add content to the <head> section.

There are quite some ways of adding content to head tag programmatically. Today we are going to discuss 3 of them −

  • Using jQuery's .append() method −

  • Using JavaScript's document.createElement() method −

  • Using JavaScript's insertAdjacentHTML() method −

Using these 3 ways the same task can be achieved i.e., to add content to <head /> tag of a HTML file.

Therefore, let’s discuss these approaches one by one.

Approach 1: Using jQuery's .append() method

Here is a simple one liner code to append content to any tag in HTML (in our case it will be the head tag) −


Approach 2: Using JavaScript's document.createElement() method

Using the JavaScript createElement() function and then the appendChild() function we can achieve the same functionality like this −

var script = document.createElement("script");
script.innerHTML = "alert('hello');";

Approach 3: Using JavaScript's insertAdjacentHTML() method

The last way we are going to discuss is the JavaScript’s insertAdjacentHTML() method −

document.head.insertAdjacentHTML("beforeend", "");

Now that we discussed all these approaches separately, let’s use them in a working example.


The complete code is as follows −

   <title>Content in head section</title>
      <h1 style = "color: black;">Welcome to my website</h1>  
   <script src="">
         // Using jQuery's .append() method
         $("head").append("<link rel='stylesheet' href='styles.css'>");
         // Using JavaScript's document.createElement() method
         var meta = document.createElement("meta"); = "description";
         meta.content = "This is my website";

Updated on: 06-Feb-2023


Kickstart Your Career

Get certified by completing the course

Get Started