javirs
javirs

Reputation: 1100

dynamic html content from javascript (using jquery methods)

jquery is loaded in my html prior to my js code. Then in my puzzle.js I have :

class Puzzle {
  constructor(ID, Name, Status) {
    this.ID = "main" + ID;
    this.Name = Name;
    this.Status = Status;
    this.mainDiv = "";
  }

  generateDiv() {
    this.mainDiv = '<div id="' + this.ID + '"/>';
    $(this.mainDiv).addClass("puzzle");
  }
}

$(document).ready(function() {
  var puzzle = new Puzzle(1, "MyPuzzle", 1);
  puzzle.generateDiv();
  $("#Puzzles").append(puzzle.mainDiv);
})
.puzzle {
  width: 200px;
  height: 200px;
  background: black;
  border 1px solid white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Puzzles"></div>

And the div get's added with the nice ID field but the class does not. In fact anything I do to the div "jquery-style" does nothing (but also no console error)

I noticed that in the inspector (chrome) the div appears as

<div id="main1"></div> == $0

Not sure what it means or if relevant.

What am I doing wrong ???

Upvotes: 0

Views: 57

Answers (1)

Barthy
Barthy

Reputation: 3231

You need to store the jQuery version of the div:

this.mainDiv = $(this.mainDiv).addClass("puzzle");

Otherwise you add the class to something that is discarded in the next line.

Taking into account what's discussed here:

var $div = $("<div>", {id: "foo", "class": "a"});

And Mark Baijens' comment:

It's common to prepend a dollar sign to variables that contain jQuery objects

You could do something like the following:

class Puzzle {
  constructor(ID, Name, Status) {
    this.ID = "main" + ID;
    this.Name = Name;
    this.Status = Status;
    this.$mainDiv = null;
  }

  generateDiv() {
    this.$mainDiv = $("<div>", {id: this.ID, "class": "puzzle"});
  }
}

$(document).ready(function() {
  var puzzle = new Puzzle(1, "MyPuzzle", 1);
  puzzle.generateDiv();
  $("#Puzzles").append(puzzle.$mainDiv);
})
.puzzle {
  width: 200px;
  height: 200px;
  background: black;
  border 1px solid white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Puzzles"></div>

Upvotes: 2

Related Questions