Node.innerHTML giving tag names in lower case

筅森魡賤 提交于 2019-12-01 19:55:51

You cannot count on .innerHTML preserving the exact nature of your original HTML. In fact, in some browsers, it's significantly different (though generates the same results) with different quotation, case, order of attributes, etc...

It is much better to not rely on the preservation of case and adjust your javascript to deal with uncertain case.

It is certainly possible to use a regular expression to do a case insensitive search (the "i" flag designates its searches as case insensitive), though it is generally much, much better to use direct DOM access/searching rather than innerHTML searching. You'd have to tell us more about what exactly you're trying to do before we could offer some code.

It would take me a bit to figure that out with a regex, but you can use this:

    var str = '<panel><label>test</label></panel>';
    chars = str.split("");
    for (var i = 0; i < chars.length; i++) {
        if (chars[i] === '<' || chars[i] === '/') {
           chars[i + 1] = chars[i + 1].toUpperCase();
        }
    }
    str = chars.join("");

jsFiddle

I hope it helps.

If you are trying to just capitalise the first character of the tag name, you can use:

var s = 'panel';
s.replace(/(^.)(.*)/,function(m, a, b){return a.toUpperCase() + b.toLowerCase()}); // Panel

Alternatively you can use string manipulation (probably more efficient than a regular expression):

s.charAt(0).toUpperCase() + s.substring(1).toLowerCase(); // Panel

The above will output any input string with the first character in upper case and everything else lower case.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!