Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly.

function createTH(){
  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 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.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again"/>

Upon clicking the button for the second time, the output of my code becomes chaotic.

I aim to achieve the following output pattern:

<tr>
...
<th><td><td>//I only want to repeat this single line on every click of the button.
<th><td><td>
<th><td><td>//I'm looking to create this kind of repetition on the click of the button.
...
</tr>

For further details, you can refer to: Dynamic Creation of th. This question serves as a follow-up to the previous discussion thread. Creating a new thread was necessary due to the complexity and length constraints of the original question.

Your assistance in resolving this issue would be highly appreciated.

Answer №1

The issue is arising because you are appending thContent to every single tr element that is selected by jQuery, instead of just the new one. To resolve this, modify the line so that it only appends to the new instance of row:

$(row).prepend(thContent);

It's important to mention that your code incorporates a mix of plain JavaScript and jQuery methods. If you are already utilizing jQuery, you can significantly streamline the code:

$('#add').on('click', function() {
  var rowHtml = '<tr><th class="col2"><br />test&nbsp; &nbsp;*</th><td>this is inside table div</td><td>this is inside another another div</td></tr>';
  $('#addItemTable').append(rowHtml);
});
td { border: dashed; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody></tbody>
  </table>
</div>
<button id="add">Click to create &lt;th&gt; again and again</button>

Answer №2

Continuously include new elements to each row.

Consistently utilize jQuery for efficiency. Remember the DRY principle: Do not repeat yourself.

Just like this:

const cellStyle = { "style": "border: dashed;" }

$("#addRow").on("click", function() {
  const $tb = $("#addItemTable tbody");
  let $newRow = $("<tr>");
  $newRow.append('<th class="col2"><br />test  *</th>');
  $newRow.append($("<td>", cellStyle).text("this is inside table cell"));
  $newRow.append($("<td>", cellStyle).text("this is inside another table cell"));
  $tb.prepend($newRow);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>
<input type="button" id="addRow" value="Click to create <tr> again and again" />

Answer №3

If you want to increase the index number of a row and append data in it when a function is called, you can use a row counter.

Check out this Demo:

var rowCounter = 0;
function createTH(){
  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 div";
    cell3.style="border: dashed;"
    var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
    var mainTable = document.getElementById("addItemTable");
    $('#addItemTable>tbody>tr').eq(rowCounter).prepend(thContent);
    rowCounter++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again"/>

Answer №4

My unique solution to this problem involved utilizing the concept of Outer Html. It was a different perspective that helped me find another way to approach the question.

function generateTableHeader() {
  var rowCount = document.getElementById("addItemTable").rows.length;
  var temporary = document.getElementById("addItemTable");
  var tableBody = temporary.getElementsByTagName('tbody')[0];
  var newRow = tableBody.insertRow(-1);
  var cell1 = newRow.insertCell(0);
  var cell2 = newRow.insertCell(1);
  var cell3 = newRow.insertCell(2);
  elementValue = '<th class="col2">' + "test" + '&nbsp &nbsp' + '*' + '' + '</th>';
  cell1.outerHTML = elementValue;
  cell2.innerHTML = "this is inside table div";
  cell2.style = "border: dashed;"
  cell3.innerHTML = "this is inside another another div";
  cell3.style = "border: dashed;"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>
<input type="button" onclick="generateTableHeader()" value="Click to create <th> again and again" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the Bootstrap datetimepicker malfunctioning without any console errors to indicate a potential conflicting script?

http://www.pierceresults.com/pierce-results-seminars/PRS-Level-1-October-2015-Marietta-GA When using OpenCart, I encountered an issue with a time field for registrants to select an appointment time. The time, date, and datetime option types are not functi ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = Objec ...

Populate a select list in real time with dynamically generated options

I'm facing a challenge at the moment; I am using JavaScript to dynamically generate select boxes, however, I require Ajax to populate them with options. At the moment, my code is returning undefined and I am unsure of how to proceed. While my PHP succ ...

Adding information to an array within a document in a MongoDB database

I am facing an issue where I am trying to add data to the readBook array in my User collection document. The code and console.log seem to indicate that the User is retrieved from the database and there is data to push, but nothing changes after the code ex ...

I would like to know the method for inserting an HTML element in between the opening and closing tags of another HTML element using

Recently, I came across a coding challenge involving a textbox. <input type="text></input> The task was to insert a new span element between the input tags using jQuery, as shown below: <input type="text><span>New span element< ...

Replace specific text with a span element around it?

I am working with the following HTML code: <p class="get">This is some content.</p>. My goal is to modify it so that it looks like this: <p class="get">This is <span>some</span> content.</p>. To achieve this, I have ...

The local copy of Jquery.min.js is failing to trigger the window load function

Recently, I encountered an issue with the focus of tabs while working with jQuery. Initially, everything was fine when I included: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> in my JSP file. The wi ...

How to use jQUERY to retrieve the parent directory of a given URL

Is there a way to use Ajax in loading an xml file that is situated in a different folder within the root directory? Could someone guide me on how to retrieve the root directory path using jQuery? What is the best method to navigate to the parent direct ...

Dynamic Automatic URL Refresh with Javascript

Hey there! Just joined this community and I'm still a coding newbie. I'm trying to figure out how to make an external JavaScript URL automatically refresh every 30 seconds. The URL looks something like this: domain.com/filename.js The tricky pa ...

Handling and iterating through unfamiliar objects in AngularJS

I've been exploring the concept of generics in ASP.NET MVC for a while now, and it got me thinking about how generics are used in other languages like AngularJS. Let's say I have 2 endpoints to work with: www.listofstudents.com/all and www.list ...

Challenges arise when attempting to return an early resolution within promises in JavaScript

I have a function that determines further execution within itself and needs to use promises since it is asynchronous. An issue arises where the function continues execution even after resolving. Here's my code: function initializeApplication() { ...

The plugin that simplifies adding and removing form fields in jQuery

I am in search of a quality plugin that can easily add or remove a set of form fields on a webpage. I came across this one , which seems to fit my requirements. However, I am exploring other options to see if there is an even better plugin available. Ther ...

Achieving Vertical Center Alignment in CSS

I'm having trouble understanding what's happening here: My goal is to vertically center an iframe and another div, both positioned alongside each other horizontally. What I've attempted is placing the iframe and div inside a new div called ...

Issues with AJAX form submission functionality

I have attempted various methods, but every time I try to submit a form using ajax, the page reloads and nothing gets submitted. No success or error message is returned - it appears that the function isn't even being executed. Below is the code, tha ...

Steps for adding a forked version of a library in package.json

Recently, I came across a React JS library called React Pacomo. Since the original version of this library is no longer being maintained, I decided to use my own forked version for my project. However, I am facing issues with compiling or building the libr ...

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

Utilizing Jquery's replacewith function to extract and read the id value

In this script, changing the dropdown list populated with opt1/opt2 triggers an alert displaying the ID as 'drop'. However, when I click on the 'clickme' text entry box, it transforms into a new dropdown. Yet, there is no alert issued ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...

Content will be loaded only after the user clicks on the item

On my blog, I have a share button that displays different social media platforms when clicked. However, the page takes longer to load due to fetching data from multiple servers like Facebook and Twitter. Is there a way to use jQuery to make these buttons l ...

Use an EditText to capture user input, then pass the variables to a Webview by executing a javascript command

I'm currently working on a basic web application that aims to streamline the user experience by eliminating the need for repeated credential input upon website access (without saving passwords). After some exploration, I was able to identify and manip ...