javascriptfor-loopwhile-loophtml-tableunwrap

Removing table tags and preserving <td> innerHTML in SharePoint list using JavaScript for loop


I have a SharePoint list/table, i want to remove the all table tags or you can say unwrap all of my innerHTML inside all "td", so i can design the UI of that content. I have code, when i run this code it works a once, i want help to make some kind of for loop which will remove all the table tags and keep innerHTML of all "td"

/* Code Start */

var tableTags = document.querySelector('.ms-listviewtable td');

// get the element's parent node

var parent = tableTags.parentNode;

// move all children out of the element

while (tableTags.firstChild) parent.insertBefore(tableTags.firstChild, tableTags);

// remove the empty element

parent.removeChild(tableTags);

/* Code End */

JS Fiddle Link for Full Code: https://jsfiddle.net/AzadKolachi/doh2j5wy/1/


Solution

  • To remove all the table tags and keep the innerHTML of all "td" elements in a SharePoint list or table, you can use a loop to iterate over all the "td" elements and unwrap their contents. Here's the modified code:

    var tdTags = document.querySelectorAll('.ms-listviewtable td');
    
    // Iterate over each "td" element
    tdTags.forEach(function(td) {
      // Get the parent node
      var parent = td.parentNode;
    
      // Move all children out of the "td" element
      while (td.firstChild) {
        parent.insertBefore(td.firstChild, td);
      }
    
      // Remove the empty "td" element
      parent.removeChild(td);
    });
    

    This code uses the querySelectorAll method to select all the "td" elements in the SharePoint list/table. Then, it iterates over each "td" element using the forEach method. Inside the loop, it performs the same unwrapping process as in your original code.

    By running this modified code, it will remove the table tags and keep the innerHTML of all "td" elements, allowing you to design the UI using the extracted content.

    Additionally, you can check out this code:

    document.querySelector('.ms-listviewtable > thead').remove();
    
    let rows = document.querySelectorAll('.ms-listviewtable > tbody > tr');
    
    for (const row of rows) {
        for (let i = 0; i < 3; i++) {
            row.removeChild(row.firstElementChild);
        }
    }
    
    var tableTags = document.querySelectorAll('.ms-listviewtable td');
    
    for (const td of tableTags) {
        var parent = td.parentNode;
        while (td.firstChild) {
            parent.insertBefore(td.firstChild, td);
        }
        parent.removeChild(td);
    }