Nathan
Nathan

Reputation: 384

Insert just a closing tag before an element?

Take some code, such as:

<div class="container"> <!-- my CSS centers me to 50% of the page width -->
    <div class="child-element"> <!-- I am nice and centered inside of .container -->
        <p>Hello world.</p>
    </div>
    <div class="full-width"> <!-- I want to break free of the 50% .container -->
        <p>I should be the entire width.</p>
    </div>
</div>

I do not have control of the HTML output in general.

So I want to do something like the following with jQuery.

$('</div><!--test-->').insertBefore('.full-width');
$('<div class="container"><!--test2-->').insertAfter('.full-width');

The idea is that I would then end up with this HTML:

<div class="container">
    <div class="child-element">
        <p>Hello world.</p>
    </div>
</div> <!-- This would be the result of line 1 of jQuery above -->
<div class="full-width">
    <p>I should be the entire width.</p>
</div>
<div class="container"> <!-- This would be the result of line 2 of jQuery above -->
</div> <!-- This would be the original, final closing tag in the HTML above -->

However, this just puts the <--test--> above .container and then creates a new <div class="container"> with <--test2--> inside on the page, probably because jQuery assumes things are going to break.

Is there anyway to force jQuery to just place my code and ignore whatever error checking / sanitization it's doing?

Upvotes: 0

Views: 47

Answers (1)

Nathan
Nathan

Reputation: 384

Still open to other answers on how to do this, but for now I solved like so:

if ($('. full-width').length) { // if a .full-width even exists
    $('.container').addClass('old-container').removeClass('container');
    $('.old-container > *:not(.full-width)').wrap( "<div class='container'></div>" );
}

This results in HTML like:

<div class="old-container">
    <div class="container">
        <div class="child-element">
            <p>Hello world.</p>
        </div>
    </div>
    <div class="full-width">
        <p>I should be the entire width.</p>
    </div>
</div>

Upvotes: 1

Related Questions