I am writing a script to copy the content of an element to the parent element, and delete the element. The element and the parent element have the same class. For example:
Before the script runs:
<span class='SomeClass'>
Some
<span class='SomeClass'>
Copied
</span>
Text
</span>
After:
<span class='SomeClass'>
SomeCopiedText
</span>
Below is my code. The text of element which is inside ("Copied") ends up on the end of line, not between "Some" and "Text". How can I fix it?
if ($('.SomeClass > .SomeClass').length > 0) {
$('.SomeClass > .SomeClass').each(function(index, event) {
$(this).parent().append($(this).html());
$(this).remove();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="SomeClass">
Some
<span class="SomeClass">
Copied
</span>
Text
</span>
jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.
The jQuery remove() method removes the selected element(s) and its child elements.
The insertAfter() is an inbuilt method in jQuery which is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Syntax: $(content).insertAfter(target)
The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements.
Instead of removing the original <span>
in its entirety, you can use contents()
and unwrap()
to strip the opening and closing tags.
Using this method, the $.each
and if
are unnecessary.
$('.SomeClass > .SomeClass').contents().unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="SomeClass">
Some
<span class="SomeClass">
Copied
</span>
Text
</span>
<br><br>
<span class="SomeClass">
Another
<span class="SomeClass">
Copied
</span>
Text
</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With