将HTML格式的String转化为HTMLElement的实现方法
代码如下:
<metacharset="UTF-8">
<title>Inserttitlehere</title>
</head>
<body>
<divid="content"></div>
<script>
varel=document.createElement("div");
el.innerHTML='<htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><title>titleValue</title><metaname="description"content="Itisagoodwaytolearnscience."/><metaname="keywords"content="Symfony2,Redis,PHP"/><metaname="author"content="CSDN.NET"/><metaname="Copyright"content="CSDN.NET"/></head><body>hello</body></html>';
vardescElements=el.getElementsByTagName("head");
document.getElementById("content").innerHTML=descElements.length;
</script>
</body>
</html>
1、若将script放到head元素中,则加载脚本时,尚未加载div元素,此时会出现“document.getElementById(...)为空或者不是对象”。
2、以上代码在chrome中正常支行,输出结果为5,但在IE中输出结果为0.
3、注意在js中定义数据不需要使用[],否则会出错。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语