JSFiddle - React, Tailwind, and code Playground
by Mike McCaughan
HTML
<div>
<p>Some other text</p>
<p>Preamble, blah, blah, blah,
<div class="needed">
<input type="text" />
</div>, postamble, some other crap,
<select id="select">
<option></option>
<option value="1">one</option>
</select>.</p>
<p>Some other text</p>
</div>
<button id="fixme">Fix Deranged HTML</button>
CSS
.needed {
display: inline-block;
}
JavaScript
function fixFaultyHtml() {
var $faulties = $('p').filter(function (index) {
var $nextDiv = $(this).next('div'),
$emptyAfter = $nextDiv.nextUntil('p:empty');
return $nextDiv.length > 0 && $emptyAfter.length > 0;
});
$faulties.each(function (index, element) {
var $faulty = $(element),
$nextAfterFaulty = $faulty.nextUntil('p:empty').next().last(),
gotFaulty = false,
gotNextAfterFaulty = false,
$contents = $faulty.parent().contents().filter(function () {
if (!gotFaulty) {
gotFaulty = this === $faulty[0];
}
if (gotFaulty && !gotNextAfterFaulty) {
gotNextAfterFaulty = this === $nextAfterFaulty[0];
}
return gotFaulty && !gotNextAfterFaulty;
}).not($faulty);
$faulty.append($contents.detach());
$nextAfterFaulty.remove();
});
}
$('#fixme').on('click', fixFaultyHtml);