Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an element extend outside its parent with jQuery

I'm working with some mark-up where we have a number of html blocks/controls sitting within an outer container, this container is basically a foundation row with a max-width.

In certain situations I need blocks to break out of this container, to extend beyond the max-width and occupy the full width, but remain in it's original position in terms of index. Stay with me! This looks as follows:

<div class="row">
    <div><em>Regular block here</em></div>
    <div class="full-width"><em>Full width block here</em></div>
    <div><em>Regular block here</em></div>
</div>

In effect what I want to have is as follows:

<div class="row">
    <div><em>Regular block here</em></div>
</div>       
<div class="full-width"><em>Full width block here</em></div>
<div class="row">
    <div><em>Regular block here</em></div>
</div>

Unfortunately we don't have access to do this properly in html so jQuery looks our best bet.

I tried doing something like this, but to no avail as it's not correctly formatted html:

$('div.row > .full-width').each(function() {
    $(this).before('</div>').after('<div>');
});

Anyone got any ideas of achieving this, without completely writing the whole DOM out again, otherwise I'll have to reapply a load of bindings.

Thanks in advance.

like image 570
user1408133 Avatar asked Sep 22 '15 16:09

user1408133


1 Answers

DEMO

First unwrap() the .full-width element. This remove the main .row, then wrap() the next and previous elements in .row.

$('div.row > .full-width').each(function() {
  var $rowDiv = $('<div class="row">');
  $(this).unwrap('.row');
  $(this).prev().wrap($rowDiv);
  $(this).next().wrap($rowDiv);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div><em>Regular block here</em></div>
    <div class="full-width"><em>Full width block here</em></div>
    <div><em>Regular block here</em></div>
</div>
like image 136
rrk Avatar answered Oct 30 '22 20:10

rrk