Hide SharePoint list column

Sometimes we need to hide specific SharePoint columns in a list view webpart. The following code will help with that.
Make sure this code is placed in a JS file and referenced using JSLink webpart property.
Just replace the HideColumn function’s array parameters [“Title”, “Created By”] with necessary column’s display names.

(function () {
    var overrideCurrentContext = {};
    overrideCurrentContext.Templates = {};
    overrideCurrentContext.OnPostRender = PostRenderer;
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);
})();

function PostRenderer(ctx) {
    HideColumn(["Title", "Created By"],true);
}

function HideColumn(columns, hideOnlyHeader) {
    columns.forEach(function(columnName) {
        headerParentFirstNode = document.querySelectorAll("[displayname='" + columnName + "']")[0];
        if (headerParentFirstNode != undefined) {
            var header = headerParentFirstNode.parentNode;
            header.style.display = "none";
            if (!hideOnlyHeader) {
                var index = [].slice.call(header.parentNode.children).indexOf(header) + 1;
                for (var i = 0, cells = document.querySelectorAll("td:nth-child(" + index + ")"); i < cells.length; i++) {
                    cells[i].style.display = "none";
                }
            }
        }
    });
}

 


Leave a Reply

Your email address will not be published / Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.