1

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.

jopfre
  • 530
  • 3
  • 12
  • What's the question? How to simplify your method? It's pretty simple already. You could shorten it by making function createAndAppend, but it will take its place (4 lines). I suggest you to focus on writing code and read some good book in parallel. – Tommi Mar 09 '15 at 18:20
  • No, a wrapper object around the DOM objects is totally fine. – Bergi Mar 09 '15 at 18:22

2 Answers2

2

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");
Eyal
  • 532
  • 2
  • 12
  • You probably want to create `Player` inside `createPlayer` and return instance from it. – Tommi Mar 09 '15 at 18:26
1

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

Community
  • 1
  • 1
Valdis
  • 3,170
  • 2
  • 18
  • 24