本节主要介绍了将HTML格式的String转化为HTMLElement的实现方法,需要的朋友可以参考下
代码如下:
view sourceprint?01 <meta charset="UTF-8"> www.666fo.com
02 <title>Insert title here</title>
03 </head>
04 <body>
05 <div id="content"></div>
06 <script>
07 var el = document.createElement("div");
www.888ix.com
08 el.innerHTML = ' <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>titleValue</title> <meta name="description" content="It is a good way to learn science." /> <meta name="keywords" content="Symfony2,Redis,PHP" /> <meta name="author" content="CSDN.NET" /> <meta name="Copyright" content="CSDN.NET" /> </head> <body> hello</body> </html>';
09 var descElements = el.getElementsByTagName("head");
10 document.getElementById("content").innerHTML = descElements.length;
11 </script>
12 </body>
13 </html>
1、若将script放到head元素中,则加载脚本时,尚未加载div元素,此时会出现“document.getElementById(...) 为空或者不是对象”。
2、以上代码在chrome中正常支行,输出结果为5,但在IE中输出结果为0.
3、注意在js中定义数据不需要使用[],否则会出错。
代码如下:
view sourceprint?01 <meta charset="UTF-8"> www.666fo.com
02 <title>Insert title here</title>
03 </head>
04 <body>
05 <div id="content"></div>
06 <script>
07 var el = document.createElement("div");
www.888ix.com
08 el.innerHTML = ' <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>titleValue</title> <meta name="description" content="It is a good way to learn science." /> <meta name="keywords" content="Symfony2,Redis,PHP" /> <meta name="author" content="CSDN.NET" /> <meta name="Copyright" content="CSDN.NET" /> </head> <body> hello</body> </html>';
09 var descElements = el.getElementsByTagName("head");
10 document.getElementById("content").innerHTML = descElements.length;
11 </script>
12 </body>
13 </html>
1、若将script放到head元素中,则加载脚本时,尚未加载div元素,此时会出现“document.getElementById(...) 为空或者不是对象”。
2、以上代码在chrome中正常支行,输出结果为5,但在IE中输出结果为0.
3、注意在js中定义数据不需要使用[],否则会出错。