如何将父内容合并到他的第一个孩子中



我无法弄清楚如何使用jQuery合并他的第一个孩子中的父内容。

我想将元素的所有元素(包括文本节点)合并到其<a>子元素中。

我有这个:

<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>

我想这样做:

<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>

最后,我使用 jQuery content() 函数找到了一个解决方案:

$('.row').each(function() {
    $(this).find('a').append($(this).contents()[1], $(this).contents()[2]);
});

它不是很灵活,但它适合我的需求。谢谢大家!

评论后更新

小提琴 : http://jsfiddle.net/WaW27/

网页

<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>

简斯

$(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);
    });
});

结果:

 <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>
嗨,

你可以这样做:

var test = jQuery('.row').html().replace($("<div />").append($('.row a').clone()).html(),'');
jQuery('.row').html($('.row a').clone()).html();
jQuery('.row a').append(test);

我在这里创建了一个小提琴:

http://jsfiddle.net/j5Uqd/

最新更新