How to replace all the <td> and <td> first lines with <th> and </th> respectively, leaving intact what is inside the tags (text). I know that there is such a thing as .replace() , but I do not quite understand how to use it in this situation. Interested in a turnkey solution that allows you to change the type str

 "<tr><td>1</td><td>2</td><td>3</td></tr>" 

replaced by

 "<tr><th>1</th><th>2</th><th>3</th></tr>" 

The number of cells can be arbitrary. Thank you in advance.

  • Thank! The issue is resolved. - makbeth
  • You noticed a stupid, extremely inefficient solution. - Ridzhi
  • I would like to know the details. Why is it stupid and inefficient? - makbeth
  • one
    Because each will bypass each! td (not only in the first tr), carry out unnecessary manipulations with DOM and a comparison operation + if there are two tables on the page, then the second (and all subsequent) tables will not be replaced, since tr will not be indexed relative to table a relatively document. - Rigi

2 answers 2

 $(document).ready(function(){ $('td').each(function(){ if($(this).parent('tr').index() == 0) { $(this).replaceWith('<th>' + $(this).text() + '</th>'); } }); }); 

Or in other ways: http://forum.jquery.com/topic/how-to-change-first-row-of-td-s-into-th-s

      $('table tr:first td').each(function() { $(this).replaceWith('<th>' + $(this).html() + '</th>'); });