Search code examples
javascripthtmljqueryclone

when use JQuery clone() , why remove() not working


I use jquery clone() to copy table element , and I want to remove first td there is my code , can any one help?

javascript

$.fn.hasAttr = function(name) {  
  return this.attr(name) !== undefined;
};
var arr_tr=new Array();
$('table tr').each(function(i){
  arr_tr[i].push($(this).clone());
});
//for some reason I need use like below
for(var x in arr_tr){
  for(var y in arr_tr[x]){
    if(arr_tr[x][y].find('td:eq(0)').hasAttr('rowspan')){//if td has rowspan attribute
    arr_tr[x][y].find('td:eq(0)').remove();//<== Why [<td rowspan=3>ABC</td>] can't remove
    };
  }
}

HTML

<table border=1 width='100%'>
<tr><td rowspan=3>ABC</td><td>A2</td><td>A3</td></tr>
<tr><td>B2</td><td>B3</td></tr>
<tr><td>C2</td><td>C3</td></tr>
</table>

Solution

  • You can simplify this down to just using an attribute selector:

    const $clone = $('table').clone();
    $clone.find('td:first-child[rowspan]').remove();
    $('#res').append($clone)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table border=1 width='100%'>
      <tr>
        <td rowspan=3>ABC</td>
        <td>A2</td>
        <td>A3</td>
      </tr>
      <tr>
        <td>B2</td>
        <td>B3</td>
      </tr>
      <tr>   
        <td>C2</td>
        <td>C3</td>
      </tr>
      <tr>
        <td rowspan=2>CDE</td>
        <td>C4</td>
        <td>C5</td>
      </tr>
      <tr>   
        <td>C6</td>
        <td>C7</td>
      </tr>
      
    </table>
    
    <h3>Result</h3>
    <div id="res"></div>