简体   繁体   中英

How to get `<th>` instead of `<td>`?

I want to have first element of my row as <th> I am doing this but I am getting <td> as my first element. What I am doing wrong?

Basically I want something like this <tr><th><b>Table Header</b></th><td>item1</td><td>item2</td><\tr>

 var table = document.getElementById("data"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); $("#table td:first").append('<th><b>Table Header</b></th>');

You just need to not use insertCell in your question

 var table = document.getElementById("data"); var row = table.insertRow(-1); $(row).append('<th>Table Header</th>');
 <table id="data"></table> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

You can create your own method to insert a <th>

 // insert <TH> method, at your oxn risk HTMLTableRowElement.prototype.insert_th_Cell = function(index) { let cell = this.insertCell(index), c_th = document.createElement('th') cell.replaceWith(c_th) return c_th } //--------------------------------------- let thead = myTable.createTHead(), tBody = myTable.createTBody(), rowHead = thead.insertRow(); rowHead.insertCell() rowHead.insert_th_Cell().textContent = 'c1' rowHead.insert_th_Cell().textContent = 'c2' rowHead.insert_th_Cell().textContent = 'c3' let nRow = tBody.insertRow() nRow.insert_th_Cell().textContent = 'line' nRow.insertCell().textContent = 'AA' nRow.insertCell().textContent = 'BB' nRow.insertCell().textContent = 'CC'
 table { border-collapse: collapse; margin: 2em 1em; } td,th { padding: .2em.8em; border: 1px solid darkblue; } thead { background-color: aquamarine; } tbody th{ background-color: orchid; }
 <table id="myTable"></table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM