in the example below click on dolor
so it becomes active
then click on button – and dolor
is moved up
but in the resulting html – the new line is missing
$(document).on('click', '.ati', function(){
$('.aact').removeClass('aact');
$(this).addClass('aact');
});
$('button').on('click', function(){
let tg = $('.aact');
if(tg.length == 0){alert('TITLE IS NOT SELECTED');return;}
let tgg = tg.prev();
tg.insertBefore(tgg);
let a = $('#awrap').html();
console.log(a);
});
.aact{background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="awrap" id='awrap'>
<div class="ati">lorem</div>
<div class="ati">ipsum</div>
<div class="ati">dolor</div>
</div>
<button>CLICK</button>
result after button click:
<div class="ati">lorem</div>
<div class="ati aact">dolor</div><div class="ati">ipsum</div>
what I need is:
<div class="ati">lorem</div>
<div class="ati aact">dolor</div>
<div class="ati">ipsum</div>
how to get this ?
2
Answers
Regarding the newline the OP wants to insert, it can be done by creating and inserting a text node like …
… which changes the OP’s code to …
But the result still might not satisfy the OP since the OP wants/needs …
The latter sounds more like a sanitizing tasks where a regex based approach might be suited best.
One would go for 2 text replacements where the first one matches any closing or empty tag including an optional trailing sequence of newline characters …
/(</[^>]+>|<[^/]+/>)n*/g
… and the second trims any leading sequence of newline characters …/^n+/
… from the markup string.Try below snippet