Move Elements to Previous Div
Move elements matching certain rules to previous elements of a specific class.
by ian_smithz
HTML
<div class="row">
<div class='jt-header'>Product 1</div>
<div class='jt-detail'>Product Details
<div class='jt-item-price'>12.34</div>
</div>
</div>
<div class="row">
<div class='jt-header'>Product 2
<div class='jt-item-price'>34.45</div>
</div>
<div class='jt-detail'>Product Details</div>
</div>
<div class="row">
<div class='jt-header'>Product 3</div>
<div class='jt-detail'>Product Details
<div class='jt-item-price'>20.55</div>
</div>
</div>
<hr />
<button class="moveIt">Move Prices</button>
<button class="unwrap">Unwrap from Rows</button>
CSS
.jt-header {
clear: both;
border: 1px solid #f5f5f5;
padding: 0px .5em;
margin: .5em;
background: #f1f1f1;
}
.jt-detail,
.jt-item-price {
display: inline-block;
}
.jt-detail { padding: 1em; }
.jt-item-price {
margin: 1em 0;
background: #f1f1f1;
padding: .5em;
font-weight: bold;
}
.row {
display: block;
padding: .5em;
border: 1px solid #efefef;
}
JavaScript
/**
* Answer to: http://stackoverflow.com/questions/28661854/how-to-move-an-element-into-if-it-is-contained-in-another-element
*/
jQuery(document).ready(function(){
// Testing with no Row wrappers
jQuery('.unwrap').on('click', function(){
jQuery('.row > .jt-header').unwrap();
});
// Button required for testing purposes only
jQuery('.moveIt').on('click', movePrice);
// If script should run automatically
// move everything out of this function
function movePrice() {
// For maintaining purposes
var _price = 'jt-item-price';
var _from = 'jt-detail';
var _to = 'jt-header';
// Vudu stuff
jQuery('div.'+_price).each(function(){
// Get elements
var _this = jQuery(this);
var _parent = _this.parent();
var _parentClass = _parent.attr('class');
// If parent matches the wrapper we want
// to take the element out of
if( _parentClass == _from ) {
// Get its parent previous element
var _finalWrapper = _this.parent().prev();
// If previous element class matches our
// destination's class
if( _finalWrapper.attr('class') == _to ) {
// Put price there
jQuery(_finalWrapper).append( _this );
}
}
});
}
});