I found a few questions on here relating to my question but didn’t exactly get the answer I was looking for. I am wanting to do something like this, similar to what jQuery often does:
createCSS("mystyle.css", {
media: "screen",
type: "text/css"
});
I tried this to accomplish what I want but it’s not working:
var prop = {
media: '',
type: ''
};
function createCSS(href, prop) {
var anchor = document.createElement("link");
anchor.setAttribute("href", href);
anchor.setAttribute("media", prop.media);
anchor.setAttribute("type", prop.type);
if(typeof anchor != "undefined") {
document.getElementsByTagName("head")[0].appendChild( anchor );
}
}
Now, I know I could just create single multiple parameters like createCSS("mystyle.css", "screen", "text/css"); but I don’t like that, the other way looks cooler.
Plenty new to javascript so any help would be very much appreciated!
You don’t have to declare/initialize
var prop. Your function looks fine, just call it passing an object asprop, as in your own example:If the intention with the
var proppart was to avoid assigningundefinedto the attributes, you need a little tweak inside the function:Some minor improvements I’d suggest:
anchordoes not contain an anchor (<a>) element. Why not call itlink?if(typeof anchor != "undefined")conditional. since you’re creating the element a few lines above, that variable will never be undefined. You can skip theifandappendChilddirectly.