Node[removed] giving tag names in lower case

前端 未结 4 1917
眼角桃花
眼角桃花 2021-01-18 15:58

I am iterating NodeList to get Node data, but while using Node.innerHTML i am getting the tag names in lowercase.

4条回答
  •  粉色の甜心
    2021-01-18 16:46

    this is not thoroughly tested , and is highly inefficcient, but it worked quite quickly in the console: (also, it's jquery, but it can be converted to pure javascript/DOM easily)

    in jsFiddle

    function  tagString (element) {
        return $(element).
                clone().
                contents().
                remove().
                end()[0].
                outerHTML.
                replace(/(^<\s*\w)|(<\/\s*\w(?=\w*\s*>$))/g,
                        function (a) {
                            return a.
                                   toUpperCase();
                        }).
                split(/(?=<\/\s*\w*\s*>$)/);
    }
    
    function capContents (element) {
        return $(element).
                contents().
                map(function () { 
                       return this.nodeType === 3 ? $(this).text() : capitalizeHTML(this);
                })
    }
    
    function capitalizeHTML (selector) {
        var e = $(selector).first();
        var wrap = tagString(e);
        return wrap[0] + capContents(e).toArray().join("") + wrap[1];
    }
    
    capitalizeHTML('body');
    

    also, besides being a nice exercise (in my opinion), do you really need to do this?

提交回复
热议问题