Search code examples
javascripthtmlcssregexstylesheet

Remove background style in all html tags using javascript


How can I remove all background="..." in all HTML tags? I understood that it's not a good idea to try parsing HTML with regexes, but I don't know any over way. (tried regex "background([\s\S]*?)(;|\")" - doesn't work). Thanks.


Solution

  • By simple script you can use this code,

        <script>
        var allElements = document.childNodes;
        for (var i = 0; i < allElements.length; i++)
        {
            var currElement = allElements[i];
            if (currElement.hasAttribute("background"))
            {
                currElement.removeAttribute("background");
            }
        }
        </script>
    
    
    and to solve your mentioned issue,
    use this,
    
    use this to solve this issue,
    `<script>
            function removeBackground(cElement) {
                var allElements = cElement.childNodes;
                if (allElements.length > 0) {
                    for (var i = 0; i < allElements.length; i++) {
                        var currElement = allElements[i];
                        if (currElement.childNodes.length > 0) {
                            removeBackground(currElement);
                        }
                        if (currElement.hasAttribute("background")) {
                            currElement.removeAttribute("background");
                        }
                    }
                }
            }
         removeBackground(document);
        </script>`