首页 > 解决方案 > Dynamically created get's lower position why?

问题描述

Below is the code snippet where I've created <th> using jquery.

My question is, How can I place the dynamically created <th> above the two <td>'s which I've created below.

I've tried to search a lot but all the results where adding to the end only, not to the top of the <td>.

$(document).ready(
  function() {
    var noOfRow = document.getElementById("addItemTable").rows.length;
    var temp = document.getElementById("addItemTable");
    var table = temp.getElementsByTagName('tbody')[0];
    var row = table.insertRow(-1);
    var cell2 = row.insertCell(0);
    var cell3 = row.insertCell(1);
    cell2.innerHTML="this is inside table div";
    cell2.style="border: dashed;"
    cell3.innerHTML="this is inside another another div";
    cell3.style="border: dashed;"
    var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
    var mainTable = document.getElementById("addItemTable");
    $('#addItemTable>tbody>tr').append(thContent);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>

标签: javascriptjqueryhtml

解决方案


You must use prepend insead of append :)

$(document).ready(
  function() {
    var noOfRow = document.getElementById("addItemTable").rows.length;
    var temp = document.getElementById("addItemTable");
    var table = temp.getElementsByTagName('tbody')[0];
    var row = table.insertRow(-1);
    var cell2 = row.insertCell(0);
    var cell3 = row.insertCell(1);
    cell2.innerHTML="this is inside table div";
    cell2.style="border: dashed;"
    cell3.innerHTML="this is inside another another div";
    cell3.style="border: dashed;"
    var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
    var mainTable = document.getElementById("addItemTable");
    $('#addItemTable>tbody>tr').prepend(thContent);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>


推荐阅读