jopfre
jopfre

Reputation: 503

What is the preferred method to create a javascript object with associated dom elements?

Currently I am doing it like this:

function createPlayer(id) {
  var playerWrapper = document.createElement("div");
  document.body.appendChild(playerWrapper);

  var player = document.createElement("div");
  playerWrapper.appendChild(player);

  var Player = {
    wrapper: playerWrapper,
    player: player
  }

}

Just wondering if this is the best way or if there is some way I can create dom elements and the object at the same time? The object will also have methods attached. There will also be multiple instances of the object and associated elements.

Upvotes: 1

Views: 89

Answers (2)

Eyal
Eyal

Reputation: 532

the appendChild function returns the appended node, so you can create an empty object and assign the returned nodes directly to the object as follows: http://jsfiddle.net/v7xeLnot/1/

function createPlayer(id) {
    var Player = {}
    var playerWrapper = document.createElement('div');
    Player.wrapper = document.body.appendChild(playerWrapper);

    var player = document.createElement('div');
    Player.player = playerWrapper.appendChild(player);   

    return Player;

}
var myPlayer = createPlayer("someId");

Upvotes: 2

Valdis
Valdis

Reputation: 3178

The code itself you should write in an object oriented manner like here

Also you should use jQuery and it's append() method instead of plain document.createElement and appendChild. This will ensure cross-browser compatibility and make it easier for you to code other features too.

If you need to create a lot of html, you might consider some templateing engine

Upvotes: 1

Related Questions