How to merge parent content inside his first child?
-
21-12-2019 - |
Pregunta
I'm not able to figure out how to merge parent content inside his first child with jQuery.
I want to merge all the elements (including text node) of an element within its <a>
child.
I have this:
<td class="row">
<a href="#">
<span class="iconouter">
<img class="icon" src="...">
</span> Type of document
</a>
: Form
<span class="type-nb">(1)</span>
</td>
And I want to do this:
<td class="row">
<a href="#">
<span class="iconouter">
<img class="icon" src="...">
</span> Type of document: Form <span class="type-nb">(1)</span>
</a>
</td>
Solución
Finally, I found a solution using jQuery contents() function :
$('.row').each(function() {
$(this).find('a').append($(this).contents()[1], $(this).contents()[2]);
});
It's not very flexible, but it suits my needs. Thank you all!
Otros consejos
Updated after comment
Fiddle : http://jsfiddle.net/WaW27/
HTML :
<table>
<tr>
<td>
<a href="#">
<span class="iconouter">
<img class="icon" src="...">
</span>
Type of document
</a>
: Form
<span class="type-nb">(1)</span>
</td>
</tr>
</table>
JS :
$(document).ready(function(){
$('td').each(function(){
$content = $(this).children().first().append(
$(this).html().replace(
$('<div>').append( $(this).children().first().clone() ).html(), '' )
);
$(this).html('').append($content);
});
});
Result :
<tr>
<td>
<a href="#">
<span class="iconouter">
<img class="icon" src="...">
</span>
Type of document
: Form
<span class="type-nb">(1)</span>
</a>
</td>
</tr>
Hi you can do it that way:
var test = jQuery('.row').html().replace($("<div />").append($('.row a').clone()).html(),'');
jQuery('.row').html($('.row a').clone()).html();
jQuery('.row a').append(test);
I have created a fiddle here:
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow