Ádám Bodnár Ádám Bodnár - 2 months ago 12
HTML Question

Prepend html before html

I have an html template (jquery, js and everything is imported in the head). So here is this part, I try to prepend new paragraphs before the existing p with the id "board-page":

<div class="container">
<div class="row">
<div class="col-md-12">
<p id="board-page">some text</p>
</div>
</div>
</div>


And here is my javasript:

var boards = [];

function Board(title) {
this.title = title;
}

function appendBoards() {
for (var i in boards) {
var board = boards[i];
var title = board.title;
$("#board-page").prepend("<p>"+title+"</p>");
}
}

addNewBoardWithTitle("some other text");
addNewBoardWithTitle("other text");
appendBoards();


But this doesn't work, nothing happends. What am I doing wrong here?

Answer

You can use insertBefore for this ..

var boards = [];

function Board(title) {
   this.title = title;
 }

function appendBoards() {
    for (var i in boards) {
       var board = boards[i];
      var title = board.title;
       $("<p>"+title+"</p>").insertBefore("#board-page");
   }
}

addNewBoardWithTitle("some other text");
addNewBoardWithTitle("other text");
appendBoards();