Categories
JavaScript Answers

How to add anything in the head element with JavaScript?

Spread the love

Sometimes, we want to add anything in the head element with JavaScript.

In this article, we’ll look at how to add anything in the head element with JavaScript.

How to add anything in the head element with JavaScript?

To add anything in the head element with JavaScript, we can use the document.head.appendChild method.

For instance, we write

const favicon = document.createElement("link");
favicon.id = "myFavicon";
favicon.rel = "shortcut icon";
favicon.href = "http://www.example.com/my-favicon.ico";

document.head.appendChild(favicon);

to create the link element with createElement.

Then we set the attributes of the link element with

favicon.id = "myFavicon";
favicon.rel = "shortcut icon";
favicon.href = "http://www.example.com/my-favicon.ico";

id, rel, and href set the attribute with the same name.

And then we call document.head.appendChild with favicon to insert it into the head element as its last child.

Conclusion

To add anything in the head element with JavaScript, we can use the document.head.appendChild method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *