jQuery appendTo Parent Trouble

272 views Asked by At

First and foremost, thanks for the help in advance.

I am trying to basically lay a hovering div overtop of every anchor tag I find on a page. So i get the offset, find the height and width of each element and then create a new div and set the CSS to those measurements. I'm having trouble with the code that appends the newly created DIV to the parent of the anchor tag.

$( "a" ).each(function( index ) {
    tempoffset = $( this ).offset();
    tempheight = $( this ).height();
    tempwidth = $( this ).width();
    tempoverlay = document.createElement('div');
    tempoverlay.appendTo($(this).parent());
    tempoverlay.setAttribute("style","background: #ccc; position: fixed; height: " + tempheight + "px; width: " + tempwidth + "px; left: " + tempoffset.left + "px; top: " + tempoffset.top + "px;");
});

I am getting error that says

tempoverlay.appendTo is not a function Any thoughts on what may be happening here?

3

There are 3 answers

0
adeneo On BEST ANSWER

tempoverlay is a native DOM node, not a jQuery object, as that's what document.createElement creates, and as such it has no appendTo method.

Create jQuery objects instead

var tempoverlay = $('<div />');

tempoverlay.appendTo( $(this).parent() )
           .css({
                   background : '#ccc',
                   position   : 'fixed',
                   height     : tempheigh,
                   width      : tempwidth,
                   left       : tempoffset.left,
                   top        : tempoffset.top
               });
0
Zakaria Acharki On

Try to use append() instead since tempoverlay is not a jquery object and you can't call jquery function .appendTo on dom node:

$( "a" ).each(function( index ) {
     tempoffset = $( this ).offset();
     tempheight = $( this ).height();
     tempwidth = $( this ).width();
     tempoverlay = document.createElement('div');
     tempoverlay.setAttribute("style","background: #ccc; position: fixed; height: " + tempheight + "px; width: " + tempwidth + "px; left: " + tempoffset.left + "px; top: " + tempoffset.top + "px;");

     $(this).parent().append(tempoverlay);
});

Hope this helps.

0
Louay Alakkad On

tempoverlay is not a jQuery element. it's a dom element.

Try this: $(tempoverlay).appendTo...