Search code examples
javascriptbackbone.js

Backbone View: $el not working as expected


I have defined a View as follows:

var BookView = Backbone.View.extend({
    tagName: "div",
    className: "bookContainer",

    initialize: function() {
        this.render();
    },

    render: function() {
        this.$el.html("Hello World"); // Problem is here
        return this;
    }
});

var bookView = new app.BookView({});

The problem is, Hello World is not getting added in the specified div which I reference using this.$el.

Instead, if I do this(in render() method):

$(".bookContainer").html("Hello World");

it works fine. Why isn't this.$el referencing to $(".bookContainer")?

Note: If I log this.$el, I get following object:

[div.bookContainer, context: div.bookContainer]

Solution

  • You misunderstand how tagName and className work. From the fine manual:

    el view.el
    [...]
    this.el can be resolved from a DOM selector string or an Element; otherwise it will be created from the view's tagName, className, id and attributes properties.

    So the tagName and className properties are used to create the el, not find it in the DOM. If you want to bind your view to an existing element, use el:

    el: '.bookContainer'