Javascript DOMParser.parseFromString giving parse

2019-09-18 02:52发布

When doing this in console, why do I get a parse error?

TR = '<TR id=line1 class="myClass"><INPUT id=input1 type=hidden> <INPUT id=input2> <TD style="PADDING-LEFT: 20px" align=left> <IMG class=im border=0 src="images/img.gif"> Hello </TD><!-- comment --> <TD id=cell1 align=right></TD> <TD id=cell2 align=right></TD> <TD align=middle>&nbsp; </TD> <TD align=middle></TD></TR>';
parser = new DOMParser()
xmlDocument = _parser.parseFromString(TR, "text/xml");

2条回答
来,给爷笑一个
2楼-- · 2019-09-18 03:24

You create a new DOMParser() and assign it to a variable named parser:

parser = new DOMParser()

But then you reference an undeclared variable _parser on the next line:

xmlDocument = _parser.parseFromString(TR, "text/xml");

If you replace _parser with parser, the console error should go away.

查看更多
甜甜的少女心
3楼-- · 2019-09-18 03:29

First problem (I assume it's not the one you're experiencing, rather that this code is erroneously copy-pasted): Your variable name is parser, not _parser.

Your main problem is that you're trying to parse HTML as XML, which will work IF your HTML is also valid XML. But yours isn't. Quote your attributes for a start. That's what

error on line 1 at column 8: AttValue: " or ' expected

means.

After you do that, close your void elements. It's OK to leave off the trailing slash in HTML5, but not within the stricter rules of XML.

查看更多
登录 后发表回答