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) −

$("head").append("");

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');";
document.getElementsByTagName("head")[0].appendChild(script);

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.

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>

Updated on: 06-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements