How to add attributes dynamically in html tag using javascript function?

This article will explain how to add attributes dynamically in html page using javascript.Example: meta tag, javascript files, css files, etc

Find the javascript code for adding the html tags and attributes dynamically to html pages using javascript

Javascript Function

Below javascript function will add attribute to DOM Element using javascript “element.setattribute(attribute value)” function.

function addTag(name, attributes) {
    var el = document.createElement(name),
        attrName;

    for (attrName in attributes) {
      el.setAttribute(attrName, attributes[attrName]);
    }

    document.write(el.outerHTML);
};

Call the Javascript Function

// Add CSS file
addTag('link', {rel: 'stylesheet', href: 'css/bootstrap.min.css', type: 'text/css'});

// Add Javascript file
addTag('script', {src: 'lib/angular.min.js' });
addTag('script', {src: 'lib/angular-route.min.js' });
addTag('script', {src: 'lib/canvasjs.min.js' });
addTag('script', {src: 'lib/underscore-min.js' });
addTag('script', {src: 'js/main.js' });
addTag('script', {src: 'js/controller/controller.js' });

Output screenshot

How to add attributes dynamically in html tag using javascript function? 1

Demo

W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

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