Remove all HTML attributes from every table element

My current task involves an HTML table.

I am looking to remove all HTML attributes from the table so that it resembles the structure below:

<table>
    <thead>
        <tr>
            <th>...</th>
            ...
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>...</td>
            ...
        </tr>
    </tbody>
</table>

How can I achieve this using plain JavaScript?

I have been through various discussions on similar topics, but they often rely on jQuery (which I cannot use) or do not provide the desired outcome for me.

<table class="wikitable sortable jquery-tablesorter" style="margin-left:auto;margin-right:auto;text-align: right">
  <thead>
    <tr>
      <th data-sort-type="number" class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Rank
      </th>
      <th class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Country/Territory
      </th>
      <th class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Int$
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td align="left"><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/6/65/Flag_of_Qatar.svg/23px-Flag_of_Qatar.svg.png" decoding="async" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/6/65/Flag_of_Qatar.svg/35px-Flag_of_Qatar.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/6/65/Flag_of_Qatar.svg/46px-Flag_of_Qatar.svg.png 2x" data-file-width="1400" data-file-height="550" width="23" height="9">&nbsp;</span>
        <a
          href="/wiki/Qatar" title="Qatar">Qatar</a>
      </td>
      <td>128,378
      </td>
    </tr>
    <tr>
      <td>—</td>
      <td align="left"><i><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/6/63/Flag_of_Macau.svg/23px-Flag_of_Macau.svg.png" decoding="async" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/6/63/Flag_of_Macau.svg/35px-Flag_of_Macau.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/6/63/Flag_of_Macau.svg/45px-Flag_of_Macau.svg.png 2x" data-file-width="450" data-file-height="300" width="23" height="15">&nbsp;</span><a href="/wiki/Macau" title="Macau">Macau</a></i></td>
      <td>115,123
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td align="left"><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/d/da/Flag_of_Luxembourg.svg/23px-Flag_of_Luxembourg.svg.png" decoding="async" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/d/da/Flag_of_Luxembourg.svg/35px-Flag_of_Luxembourg.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/d/da/Flag_of_Luxembourg.svg/46px-Flag_of_Luxembourg.svg.png 2x" data-file-width="1000" data-file-height="600" width="23" height="14">&nbsp;</span>
        <a
          href="/wiki/Luxembourg" title="Luxembourg">Luxembourg</a>
      </td>
      <td>103,662
      </td>
    </tr>
    <!-- More rows follow -->
  </tbody>
  <tfoot></tfoot>
</table>

Answer №1

In order to extract attribute names from all nodes, you can utilize the .getAttributeNames() method and then remove them using the .removeAttribute() function:

[...document.querySelectorAll('*')].forEach(node => node.getAttributeNames().forEach(attr => node.removeAttribute(attr))
<table class="wikitable sortable jquery-tablesorter" style="margin-left:auto;margin-right:auto;text-align: right">
<thead><tr>
<th data-sort-type="number" class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Rank
</th>
<th class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Country/Territory
</th>
<th class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Int$
</th></tr></thead><tbody>
// Table content continues...
</tbody><tfoot></tfoot></table>

Answer №2

Here is the modified code to preserve only the country names:

<div id="tableContainer">
  <table class="wikitable sortable jquery-tablesorter" style="margin-left:auto;margin-right:auto;text-align: right">
    <thead>
      <tr>
        <th data-sort-type="number" class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Rank
        </th>
        <th class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Country/Territory
        </th>
        <th class="headerSort" tabindex="0" role="columnheader button" title="Sort ascending">Int$
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td align="left">Qatar</td>
        <td>128,378
        </td>
      </tr>
      <tr>
        <td>—</td>
        <td align="left">Macau</td>
        <td>115,123
        </td>
      </tr>
     
    </tbody>
    <tfoot></tfoot>
   </table>
</div>

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

A guide on transferring radio button values to another program and saving them into a database with the help of PHP and jQuery

I have encountered an issue with storing radio button values in a database. Specifically, I want to assign the value of 1 for "Yes" and 0 for "No". To accomplish this, I am utilizing two scripts - a.php and b.php. The former obtains the radio button values ...

unable to assign values to this.props (appears as undefined or an empty array)

Upon setting up react/redux, I encountered a peculiar issue. When my component mounts, it should render the information stored in this.props.heroes.data. However, upon logging this data, I receive an unexpected value of [{id:1,heroname:'Batman',r ...

The command "Npm Start Causes sleep is not accepted" just popped up

After cloning a React project from GitHub, I proceeded to run npm install, which successfully installed the node_modules folder. However, upon trying to run npm start, I encountered the following error: 'sleep' is not recognized as an internal or ...

Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this: <script> export default { props: ['title'], data() { return { } } } </script> After completing a specific action, I need to pro ...

What is the best way to identify duplicate keys in fixed JavaScript objects?

My approach so far has been the following: try { var obj = {"name":"n","name":"v"}; console.log(obj); // outputs { name: 'v' } } catch (e) { console.log(e); // no exceptions printed } My goal is to detect duplicate keys within a ...

Visual Studio Code's Intellisense is capable of detecting overloaded functions in JavaScript

What is the best way to create a JavaScript overload function that can be recognized by Visual Studio Code IntelliSense, and how can this be properly documented? A good example to reference is Jasmine's it() function shown below: function it(expecta ...

Is it possible to delay Vue rules from validating until a user interacts with an element?

For a project I am working on, I have implemented a v-date-picker where users can select a departure date and a return date. Interestingly, while most of the input field validations only occur after user interaction, the departure date picker displays an e ...

Press the Text and Alter Text with React

I'm having an issue with the onClick event using React hooks. My goal is to have the text change to a different one when the user clicks, and then revert back to the original text on another click. For example, clicking "Change First" should switch it ...

struggling with handling form data in Express/Node application

Currently this is my setup: Below is the Post method I am using app.post('/barchartentry', function(req, res){ res.render('barchart', { title: 'EZgraph: Bar Chart', barValues: req.body.myInputs, labelValues: req.body ...

Is it recommended to incorporate "return" in my callback function when coding in JavaScript?

Utilizing asynchronous functions in my JS application, I've encapsulated them within my own functions that take callback inputs. One question that I have is whether or not it's necessary to use the "return" keyword when calling the callback funct ...

Tips for transferring a data table (an object) from a JavaScript file to Node.js

On my HTML page, there is a table displaying student names and information, along with controls to manage the table. I created a save button to save this table as an object named SIT in my JavaScript code. I was able to manually save this table in MongoDB ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

Issue with Material UI select element not updating in onChange event of a dynamic form

Currently, I am developing a dynamic form that requires loading extra fields through JSON. However, I am facing a problem as the <Select> and <Radio> elements are not re-rendering after the value is changed. The form itself is a functional comp ...

Load Ajax file smoothly without any flickering

I am working on a webpage that automatically loads data. The script I found on a tutorial website has a flaw - the text keeps blinking every few seconds. Is there a way to prevent this blinking effect? I am new to Ajax and finding it confusing. Below is t ...

Is it possible to transform all scripts into a React component? (LuckyOrange)

I am currently working on converting the script for a specific service (http://luckyorange.com/) into a component. The instructions say to place it in index.html within the public folder, but that appears to be insecure. I'm uncertain whether this tas ...

"Exploring the ThreeJS library's ability to rotate objects within

I have a collection of individual objects in an Array that I want to rotate as a single object. Here is an example: //retrieve body parts from the console bodyParts //Result [THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.M ...

Is it possible to verify if an event occurred within a specific hour, regardless of the date using Moment.js?

I am in the process of monitoring the usage patterns of a device and displaying users their usage trends by the hour. Essentially, I need to analyze times documents to determine if the device was active between specific hour intervals, such as 6pm to 7pm, ...

What could be causing my PrimeReact dropdown component to ignore the custom class styles?

Within my Project, I am utilizing multiple Prime React dropdown components and I am aiming to customize one of them with a unique style. In my CSS, I have established global styles to overwrite the default settings for all the dropdowns. However, when tryi ...

Is it possible to invoke the created() function in Vue from another method?

Currently, I am developing an application in Vue. Upon loading the page, a cookie containing the user's zip code is retrieved and used to perform a search. However, users should also have the ability to change their zip code if it is incorrect. I woul ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...