How can I pass an object as a parameter in Javascript?

I found several questions regarding my question, but didn't exactly get the answer I was looking for. I want 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 doesn't work:

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 can just create single multiple parameters like createCSS("mystyle.css", "screen", "text/css");

, but I don't like that, the other way looks colder.

Lots of new to javascript, so any help would be much appreciated!

+3


source to share


2 answers


You don't need to declare / initialize var prop

. Your function looks ok, just call it passing an object prop

like in your own example:

createCSS("mystyle.css", {
    media: "screen",
    type: "text/css"
});

      

If the intent with the part var prop

was to avoid assigning attributes undefined

, you need to tweak a little 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 suggest:

  • Your variable anchor

    does not contain an anchor ( <a>

    ) element . Why not name it link

    ?
  • You don't need a conditional if(typeof anchor != "undefined")

    . since you are creating an element multiple lines higher this variable will never be undefined. You can directly skip if

    and appendChild

    .
+10


source


"I tried this to accomplish what I want, but it doesn't work."

The way you pass your subject is fine. While there are some interesting options in the function, it does what you ask. However, have you checked the link you created? It lacks a directive rel

, which is a requirement.



You can change your function like 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 );

      

+4


source







All Articles