Skip to content Skip to sidebar Skip to footer

Does JQuery Have A "move" Function? Or Is There A More Compact Way Of Doing This?

When using JQuery in conjunction with a content management system, I find myself often writing snippets of code such as $(document).ready(function() { var thishtml = $('#some-

Solution 1:

This should suffice:

$(document).ready(function()
{
    $('#hmpg-btm-box-holder').prepend($('#some-element'));
});

I'd avoid using outerHTML whenever possible (and preferably innerHTML also, unless you e.g. receive some HTML from a trusted server via AJAX and want to include it in the document).

Converting an element from an Element to a string (HTML) representation and back into an Element can easily cause unwanted effects like removing all event handlers attached to it.


Solution 2:

It is a simple one-liner to insert/move a single DOM element as first child of another element.

$('#hmpg-btm-box-holder').prepend($('#some-element'));

Or if you want to attach as last child:

$('#hmpg-btm-box-holder').append($('#some-element'));

Note that in both cases, the DOM element specified in the parameter will be removed from existing location in DOM if applicable.

This only applies to selectors which resolve to a single DOM element. The behavior is a bit different for case where collections are passed as a parameter, so reference the function documentation to better understand that.


Solution 3:

You can also use .replaceWith().

$('.original').replaceWith('.new');

Post a Comment for "Does JQuery Have A "move" Function? Or Is There A More Compact Way Of Doing This?"