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
Leave a Reply