Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  151] [ 2]  / answers: 1 / hits: 20878  / 12 Years ago, fri, february 1, 2013, 12:00:00

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!


More From » jquery

 Answers
3

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:




  • Your variable anchor does not contain an anchor (<a>) element. Why not call it link?

  • You don't seem to need the 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.


[#80469] Thursday, January 31, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
;