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

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

Bootstrap CDN causing modals to fail to appear

Here are the stylesheets I am currently using: script(src="/js/application.js") script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js") script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js") link(rel="styl ...

How can I transfer Gmail message using express rendering parameters?

Using passport-google-oauth for authentication and the node-gmail-api for fetching gmail, I aim to display gmail message after authentication. In order to achieve this, I have written the following code in routes.js: app.get('/profile', isLogged ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

Move the cursor to the bottom of a div that can be edited

I have been struggling to position the cursor at the end of the next or previous editable content tag if the current one is empty. However, when I try to set focus, it always ends up at the beginning of the text instead of the end. I've tried various ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

What is the best way to extract text from a list item in an unordered list (

I am trying to search a ul list that populates a ddSlick dropdown box. ddSlick adds pictures to list items, making it a visually appealing choice. To see more about ddSlick, you can visit their website here: Here is the code I am using to loop through the ...

jQuery selector for attributes with values that are higher than a specific amount using the ">" symbol or lower than a certain value using the "<" symbol

I currently have several div elements with the following structure: <div class="roomnamecta" data-price="1189" data-adult="3">Room 1</div> <div class="roomnamecta" data-price="578" data-adult ...

What is the process of creating a MaterialUI checkbox named "Badge"?

Badge API at https://material-ui.com/api/badge/ includes a prop called component that accepts either a string for a DOM element or a component. In my code: <Badge color="primary" classes={{ badge: classes.badge }} component="checkbox"> <Avatar ...

AngularJS's ng-click function seems to be malfunctioning

Currently, I am in the process of learning angularJS with the help of the book titled "Learning Web Development with Bootstrap and AngularJs." One challenge I am facing is creating a ng-click functionality for a button in my project. Unfortunately, when I ...

Remove an element from an array within objects

Need help with removing specific items from an array within objects? If you want to delete all hobbies related to dancing, you may consider using the splice method const people = [{ id: 1, documents: [{ ...

Choose the elements that do not possess a specific class as their ancestor

I'm facing an issue with my HTML code. Here's what it looks like: <div class="asd"> <audio src="..."> </div> <audio src="..."> <audio src="..."> <audio src="..."> My goal is to select all of the audio el ...

Guide on how to have controller wait for promise to be resolved by an Angular service

Currently, I have a service that initiates an AJAX request to the backend. Service: function RetrieveCompanyDataService(options) { this.url = '/company'; this.Companies = undefined; this.CompaniesPromise = ...

Discover a corresponding object within an array

I am currently dealing with an array of objects in Javascript where I need to verify if a certain value exists within any object and return the corresponding id. The issue arises when using the some() function as it only seems to match the first object. T ...

iOS 8 requires the use of a numeric keyboard for entering passwords

Is there a way to ensure that iOS displays a numeric keyboard for my password field? Currently, I am utilizing the following code: <input type="password" pattern="\d*" name="pass"/> This method was effective in iOS7, however, it seems that the ...

What is the method for a HTML button to trigger the execution of a Selenium (Java) code located in a remote location through a

I need to run a Selenium Code written in Java from a NAS (Network Attached Storage) or another connected machine. My goal is to create a web page with a button that, when clicked, triggers the execution of the Selenium script located on the connected mac ...

The JTSage date box is not visible when there is no input field being displayed

Currently, I am attempting to integrate the JTSage date box into my modal window. When I use the standard method (displaying the input text and clicking the input field), the date box appears as expected. However, I am trying to implement the No Input Di ...

Challenges with implementing asynchronous functions in NestJS controllers

Currently, I am in the process of developing a finance tracker application that involves importing data from a CSV file. The import functionality checks if an entry already exists in the database, adds a specific category to it if not found, and then saves ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

Determining When the Collapse Transition in Material UI 5 is Complete

Snippet <Collapse in={expanded} onTransitionEnd={() => console.log('finished')} > <div>foo</div> </Collapse> Error Detection The callback function (onTransitionEnd) is not triggered af ...