Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element and insert its text into parent element in the same place with jQuery

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>
like image 736
Kacper G. Avatar asked Aug 22 '17 15:08

Kacper G.


People also ask

How remove and append in jQuery?

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.

Which method is used to remove the element from set content in jQuery?

The jQuery remove() method removes the selected element(s) and its child elements.

What is insertAfter in jQuery?

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)

Which jQuery method is used to remove the child elements from the selected element?

The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements.


1 Answers

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>
like image 180
Tyler Roper Avatar answered Nov 15 '22 17:11

Tyler Roper