user1029083
user1029083

Reputation: 191

JavaScript Create function

How can i define following object properties of html and define as a function in javascript that would return some object.

HTML:

<object id="desktop" type="application/x-desktop" width="500" height="200">
<param name="client_type" value="VISTA" /> </object>

I want to acheive something like below in javascript.So that I can call GetDesktop() function from outside of javascript.

JavaScript:

 function GetDesktop()
  {
    object.id = "desktop;
    object.type = "application/x-desktop"
     ....
     ...
    ...
   }

Upvotes: 0

Views: 102

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

My interpretation of the question is the opposite of @tkone's. Hopefully one of us is right. :)

Is this browser Javascript? If so, then why not use the HTMLElement object directly?

var obj = document.getElementById('desktop');

That gets you an object for which this is true:

obj.getAttribute('id') // -> 'desktop'
obj.getAttribute('type') //-> 'application/x-desktop' 

etc.

If you want a simple JS object with attributes that are stored directly, you can create one by looping through the DOM attributes:

   var elem = document.getElementById('desktop');
   var obj = {};
   var attrCount = elem.attributes.length;
   for (var i=0; i<attrCount; ++i) {
      var attr = elem.attributes[i];
      obj[attr.name] = attr.value
   }

That gets you an object for which this is true:

obj.id // -> 'desktop'
obj.type //-> 'application/x-desktop' 

etc.

Upvotes: 1

tkone
tkone

Reputation: 22728

You want to return the HTML above from a JS function?

var GetDesktop = function(){
    var obj = document.createElement('object');
    obj.setAttribute('id', 'desktop');
    obj.setAttribute('type', 'application/x-desktop');
    obj.setAttribute('width', '500');
    obj.setAttribute('height', '200');
    var param = document.createElement('param');
    param.setAttribute('name', 'client_type');
    param.setAttribute('value', 'VISTA');
    obj.appendChild(param);

    return obj;
}

Obviously if any of those properties need to change, you can pass them in as parameters to the function...

Upvotes: 2

Related Questions