innerHTML removes attribute quotes in Internet Exp

2019-01-11 11:29发布

When you get the innerHTML of a DOM node in IE, if there are no spaces in an attribute value, IE will remove the quotes around it, as demonstrated below:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <div id="div1"><div id="div2"></div></div>
        <script type="text/javascript">
            alert(document.getElementById("div1").innerHTML);
        </script>
    </body>
</html>

In IE, the alert will read:

<DIV id=div2></DIV>

This is a problem, because I am passing this on to a processor that requires valid XHTML, and all attribute values must be quoted. Does anyone know of an easy way to work around this behavior in IE?

7条回答
Ridiculous、
2楼-- · 2019-01-11 11:36

I might be couple year too late but here goes. Accepted answer might do what it promises but it's already Friday afternoon and I need something simpler nor I have time go it through. So here's my version which will just quote attribute values w/o quotes and it should be pretty trivial to extend it.

var t = "<svg id=foobar height=\"200\" width=\"746\"><g class=rules>";
t.replace(/([\w-]+)=([\w-]+)([ >])/g, function(str, $n, $v, $e, offset, s) {
    return $n + '="' + $v + '"' + $e;
});
查看更多
Ridiculous、
3楼-- · 2019-01-11 11:45

There is a quick and dirty workaround for this issue. I used it when working with jQuery templates. Just add a trailing space to the value of the attribute. Of course this does not make much sense with id that is used in the example, so here is another example involving jQuery, and jQuery templates:

http://jsfiddle.net/amamaenko/dW7Wh/5/

Note the trailing space in the line <input value="${x} "/> without it, the example won't work on IE.

查看更多
聊天终结者
4楼-- · 2019-01-11 11:50

did you tried with jquery ?

alert($('#div1').html());
查看更多
你好瞎i
5楼-- · 2019-01-11 11:56

I ran into this exact same problem just over a year ago, and solved it using InnerXHTML, a custom script written by someone far smarter than I am. It's basically a custom version of innerHTML that returns standard markup.

查看更多
迷人小祖宗
6楼-- · 2019-01-11 11:57

Ah, the joy of trying to use XHTML in a browser that doesn't support it.

I'd just accept that you are going to get HTML back from the browser and put something in front of your XML processor that can input tag soup and output XHTML — HTML Tidy for example.

查看更多
We Are One
7楼-- · 2019-01-11 11:57

I've tested this, and it works for most attributes, except those that are hyphenated, such as class=day-month-title. It ignores those attributes, and does not quote them.

查看更多
登录 后发表回答