Moving div above another using Javascript/JQuery?
Solution 1
Here is a little demonstration.
The insertBefore
code being used is this:
$("<div>").prop("id","between").insertBefore("#blah");
The first two jQuery functions just create the div
element. If you want to move an existing one:
$("#existingDiv").insertBefore("#otherDiv");
And this should be pretty self-explanatory.
For plugins, load jQuery asynchronously. Something like this should do:
(function(){
var s = document.createElement('script');
s.src = 'http://code.jquery.com/jquery-1.8.2.min.js';
document.getElementsByTagName('head')[0].appendChild( s );
})();
Solution 2
jQuery has a very easy method to move one node before another, which you touched upon in your question:
BEFORE:
<div id="first"></div> <div id="second"></div>
$("#second").insertBefore("#first");
AFTER:
<div id="second"></div> <div id="first"></div>
As far as Chrome, you may want to do some digging to see if jQuery is loaded by the time you make your call or not
whitfin
Know various things, the things I don't know I research, for the things I can't research I find myself here...
Updated on November 23, 2022Comments
-
whitfin over 1 year
I've seen a lot about doing this in CSS (far from ideal), but I'm thinking of building a Chrome extension and it requires that a div is inserted prior to another (for clarification, I mean that when testing the extension I need to drag the div above the other using Chrome Dev Tools). Is there a way to do this upon page load using Javascript/JQuery (or some other way which can be done via Chrome Extension)?
In previous attempts I've tried using
insertAfter()
/insertBefore()
andbefore()
and had no luck (although I might be missing something obvious), so I guess another question is do these need to be used in a certain way within a Chrome Extension?Thanks in advance for any help!
-
whitfin over 11 yearsI guess that means the issues I'm facing must be with how it's being handled by Chrome then. I figured the JQuery should work fine, but you never know!