Reputation: 3716
I am currently building a website with the Meteor framework. Right now, I am trying to get it so that when I click on an element in the DOM (rendered through handlebars), new elements are appended to the one that was currently clicked. I am doing this with jquery and have included all the proper packages. Unfortunately, when I test what I have, I get this error: Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
. I've looked around online and I can't seem to figure out why this is happening.
Here is all the relevant code with comments to explain why I'm doing what I am:
Category template (this is the element I'm trying to append to):
<template name="category">
<div class="category">
<h2 class="text-center category-title"> {{title}} </h2>
<div class="topics"> </div> <!-- where I want to append -->
</div>
</template>
Event handling code:
Template.category.events({
'click .category': function(e){
var elem = $(this > '.topics'); //grab div to append to
var category = this;
console.log(elem); //will log what appears to be a jquery object (output below)
for (var i = 0; i < category.topics.length; i++){ //loop to append all new elements
var html = '<div>' + category.topics[i] + '</div>';
elem.append(html); //this is where the error occurs
}
}
})
Log output:
[true, jquery: "1.11.0", constructor: function, selector: "", toArray: function, get: function…]
Anybody have any ideas what I'm doing wrong?
Upvotes: 2
Views: 16788
Reputation: 19544
1) This line:
var elem = $(this > '.topics')
What do you mean by this? First of all, this
here is a template data context, not a DOM element and certainly not a selector string. On top of that, you use >
comparison, which returns false
, so you're effectively left with $(false)
– probably not what you want.
To get template DOM elements you should use template methods instead of global ones. In your case, that's most probably:
var elem = t.$('.topics');
Edit: and of course, you should define your function as function(e, t)
to get the template instance here.
2) You really shouldn't manipulate DOM in that way. You miss out on reactivity, template optimizations, and everything Meteor is doing already for you. A "Meteor way" would be to have the HTML you need already in template, and toggle whether it's shown or hidden by a reactive variable.
Upvotes: 3