Reputation: 7717
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!
Upvotes: 3
Views: 20797
Reputation: 71939
You don't have to declare/initialize var prop
. Your function looks fine, just call it passing an object as prop
, as in your own example:
createCSS("mystyle.css", {
media: "screen",
type: "text/css"
});
If the intention with the var prop
part was to avoid assigning undefined
to the attributes, you need a little tweak inside the function:
function createCSS(href, prop) {
prop = (typeof prop !== "object") ? {} : prop;
prop.media = prop.media || 'screen'; // default media will be screen
prop.href = prop.href || 'text/css'; // default type will be text/css
// rest of code
}
Some minor improvements I'd suggest:
anchor
does not contain an anchor (<a>
) element. Why not call it link
?if(typeof anchor != "undefined")
conditional. since you're creating the element a few lines above, that variable will never be undefined. You can skip the if
and appendChild
directly.Upvotes: 10
Reputation: 82337
"I tried this to accomplish what I want but it's not working"
The way you pass your object is fine. Although there are some interesting choices in the function, it does what you are asking. However, have you inspected the link you create? It lacks the rel
directive which is a requirement.
You may want to change your function to this:
function createCSS(href, prop) {
var anchor = document.createElement("link");
anchor.setAttribute("href", href);
anchor.setAttribute("media", prop.media);
anchor.setAttribute("type", prop.type);
anchor.setAttribute("rel", prop.rel);
document.getElementsByTagName("head")[0].appendChild( anchor );
}
var prop = {
media: "screen",
type: "text/css",
rel: "stylesheet"
}
createCSS( "mystyle.css", prop );
Upvotes: 4