Reputation:
I'm trying to create an element on the fly and then get the center of said element. Here is what I have:
function drawnode(entity, x, y) {
var ele = ""
ele += "<div class='relNode'>";
ele += "<span>" + entity.name() + "</span>"
ele += "<div>"
var node = $(ele).appendTo('#rPaper').get(0);
var offset = node.offset();
var width = node.width();
var height = node.height();
var centerX = offset.left + width / 2;
var centerY = offset.top + height / 2;
node.css("top", centerY + y).css("left", centerX + x);
}
This gives the error
Object #<HTMLDivElement> has no method 'offset'
I originally tried it without the .get(0)
and it gives no errors but the height and width are both 0.
What am I doing wrong?
Upvotes: 0
Views: 2196
Reputation: 148140
You are trying to call jQuery
function on DOM
object as get gives you DOM
object not jQuery object Use eq()
instead of get()
to get jQuery object
var node = $(ele).appendTo('#rPaper').eq(0);
Upvotes: 3
Reputation: 2375
var node = $(ele).appendTo('#rPaper');
var offset = node.offset();
Upvotes: 0
Reputation: 388316
.get(index) returns a dom element reference which does not have methods like offset() which are provided by jQuery. so you need to use a jQuery wrapper for the element to use methods like .offset()/.width()
var node = $(ele).appendTo('#rPaper');
Upvotes: 0