Implement an onClick event to the newly created th element using document.createElement()

Through the use of document.createElement("th"), I am dynamically inserting columns into a table.

var newTH = document.createElement('th');

Is there a way to add an onClick attribute to this element so that users can delete a column by clicking on its header? Any assistance would be greatly appreciated. Alternatively, if direct application of the event listener is not feasible, can something be placed within

newTH.innerHTML

to achieve the desired functionality?

Answer №1

let createNewHeading = document.createElement('h2');
createNewHeading.innerHTML = 'Greetings, Earth!';
createNewHeading.onclick = function () {
    this.parentElement.removeChild(this);
};

let mainContent = document.getElementById('main-content');
mainContent.appendChild(createNewHeading);

Live demo: http://jsbin.com/12abc/

An alternative way to handle the element is by using this.style.visibility = 'hidden'.

Answer №2

let addTH = document.createElement('th');
addTH.setAttribute("onclick", "deleteColumn(#)");
addTH.setAttribute("id", "#");

function deleteColumn(#){
// remove the specified column #
}

Answer №3

let tableHeading = document.createElement('th');
tableHeading.onclick = function() {
      //Add your code here
}

Answer №4

let createNewTableHead = document.createElement('th');
createNewTableHead.addEventListener( 'click', () => {
  // Functionality to remove the column can be added here
} );

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

What techniques can be used to avoid the MUI `DataGrid` from constantly re-rendering when a row is committed?

Check it out here to see how the MUI documentation implemented it: <b>const</b> rows = [/* Row Data */] <DataGrid rows={rows} {/* Other Props */} /> <sup>/*[1]*/</sup> The approach taken by MUI is quite impressive. It streaml ...

Modifying Characteristics of Elements Added Dynamically

How do I change the type attribute for dynamically added buttons? In the code below, the label names are changing perfectly, but when I try to change button types, it applies to all dynamically added buttons. My requirement is to change every button type t ...

Tips for including vue-autonumeric in your webpack 2 setup

Encountering a problem while bundling the vue-autonumeric package with Webpack 2, where the dependency AutoNumeric is not being found properly. Although there is an alias set up in the configuration that works fine with webpack 3, it seems to fail when wo ...

What are the steps to implement timer control in Ajax using JavaScript?

Hello, I have been trying to establish communication with the server through my application. To achieve this, I made a call to the webservice using AJAX. Now, I am looking to incorporate a time interval in AJAX. Can anyone kindly provide guidance on how ...

What is the best way to group Angular $http.get() requests for efficiency?

My challenge involves a controller that must retrieve two distinct REST resources to populate two dropdowns. I want to ensure that neither dropdown is populated until both $http.get() calls have completed, so that the options are displayed simultaneously r ...

Merge two JSON arrays without specifying which fields to combine explicitly

After converting two Excel sheets to JSON using an online tool, two separate JSON properties were created for each sheet. The resulting JSON example looks like this: { "Product Info": [ { // Product information details here }, ...

What is the best way to choose an Animatedmodal that can showcase various demos while using just one ID?

I am currently customizing my website and utilizing the AnimatedModal.js framework. I have successfully displayed content in one modal, but encountered difficulty when attempting to create multiple modals as they all share the same ID. My question is, how ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

Is there a way to insert json data into a form input field using jQuery?

I am attempting to insert the JSON result into an input as the value. This is the code I am using: $.ajax({ type:"POST", url: '{% url "url_searchTour"%}', data: data1, success: function(jsonAjaxResult){ console.log(J ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

What are the possible complications that could arise from implementing this system for designing web pages?

Feeling frustrated with the limitations and compatibility issues of CSS, I decided to create a new approach for structuring webpages. Instead of relying on CSS, I developed a javascript library that reads layout instructions from XML files and uses absolut ...

Issue with dropdown component in material ui version v1.0 beta 26 encountered

Currently, I am encountering an issue with the dropdown component while using Material UI v1.0 beta.26. In this updated version, you are required to utilize the Select component along with MenuItem. Although my dropdown is successfully populated upon rend ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

Implementing a form submission using jQuery AJAX

Does this code look right to you? I am attempting to submit it and would like the text area to be empty again after submission. <script type="text/javascript"> $(document).ready(function(){ $("form#submit").submit(function() { // Store ...

A common inquiry: how can one pinpoint a location within an irregular figure?

I have been studying Html5 Canvas for a few weeks now, and the challenge mentioned above has puzzled me for quite some time. An irregular shape could be a circle, rectangle, ellipse, polygon, or a path constructed by various lines and bezier curves... I ...

Enhance Website User Experience: Keeping Track of Scroll Position When Users Navigate Back in Browser

Have you ever experienced the frustration of scrolling through a page with infinite scroll, only to click on a link and then go back to find that you've lost your place in the scroll? You're scrolling down a lot, You click on a link from the i ...