0

I need cut and paste text with all tags inside from main span to label element in every p tag.

<form>
    <p>
        <input...>  
        <label...>
        <span>Will trip the left<span>engin<span>e genge</span>rat</span>or only and connect external power to the left generator bus.
        </span>
    </p>
    <p>     
        <input ...>                                                                             
        <label></label><span>Will trip the left<span>engin<span>e genge</span>rat</span>or only and connect external power to the left generator bus.<br></span>
    </p>
    <input ...> 
</form>

I used this command:

$(document).find('form p').each( function(){ 
  $(this).find('span').detach().appendTo($(this).find('label'))
});

but i getting other spans outside that element. What am I doing wrong ?

i need something like this:

<form>
    <p>
        <input...>  
        <label>
            <span>Will trip the left<span>engin<span>e genge</span>rat</span>or only and connect external power to the left generator bus.
            </span>
        </label>
    </p>
</form>
Rafał Gąsior
  • 95
  • 2
  • 10

1 Answers1

1

You need to use the children method instead of the find method. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well. (see https://api.jquery.com/children/)

$(document).find('form p').each(function((){
  $(this).children('span').appendTo($(this).children('label'))
});
nmathews
  • 36
  • 4