RedGiant
RedGiant

Reputation: 4748

Don't remove content from table td first child

(JSfiddle Example)

I want to exclude the text in td first child from being removed so that the text Sale,Age remains, for example:

The original HTML:

<table class="toptable"><thead>
  <tr>
    <th class="dsdds_image">-</th>
    <th class="r3dde_image">-</th>
    <th class="s43434_image">-</th>
    </tr></thead><tbody>
  <tr>
    <td class="44665_description">Name</td>
    <td class="3434d_description">Alan</td>
    <td class="a34df_description">John</td>
  </tr>
  <tr>
    <td class="dfs4rf_title">Age</td>
    <td class="adf43df_title">8</td>
    <td class="dsffds4_title">9</td>
    </tr></tbody>
</table>

After remove(), it should be

<table class="toptable"><thead>
  <tr>
    <th class="dsdds_image"></th>
    <th class="r3dde_image"></th>
    <th class="s43434_image"></th>
    </tr></thead><tbody>
  <tr>
    <td class="44665_description">Name</td>
    <td class="3434d_description"></td>
    <td class="a34df_description"></td>
  </tr>
  <tr>
    <td class="dfs4rf_title">Age</td>
    <td class="adf43df_title"></td>
    <td class="dsffds4_title"></td>
    </tr></tbody>
</table>

I use an if statement to check if it is :first-child before the remove function but it's still clearing the first child text. Could anyone give me some suggestions?

$('#cleartable').on('click', function () {
 var clear = $(".toptable td,.toptable th")

if (clear.not(':first-child')){   //*******This part
 clear.contents().filter(function(){
    return this
   }).remove();
}
   clear.each(function() { 
   var $this = $(this)
   if ($this.attr('class')){ 
      var changeclass = $(this).attr("class");
      $this.attr('class',changeclass.replace(/^[^_]+/,"placeholder"));//See this? 
   }   

   });
});

Upvotes: 0

Views: 234

Answers (3)

danjam
danjam

Reputation: 1062

In your code you are using

if (clear.not(':first-child'))

jQuery's .not() will return a jQuery instance not boolean value, so this may not be doing what you expect.

A quick and easy way to do what you want is

clear.not(':first-child').text('');

Upvotes: 1

Try

Fiddle demo

clear.filter(function () {
        return $(this).index() !== 0; //return false for the first indexed element inside the parent
       //return !$(this).is(':first-child'); you can also use
}).remove(); //if you don't wanna remove them set empty text .text('') .

.index()

.filter()

.is()

Upvotes: 1

Vincent Decaux
Vincent Decaux

Reputation: 10714

Maybe an easy way :

var clear = $(".toptable td+td,.toptable th")

Upvotes: 1

Related Questions