A method to convert an HTML String into an HTMLElement

  • 2020-03-30 03:38:42
  • OfStack

The code is as follows:


<meta charset="UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
<div id="content"></div> 
<script> 
var el = document.createElement("div"); 
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>'; 
var descElements = el.getElementsByTagName("head"); 
document.getElementById("content").innerHTML = descElements.length; 
</script> 
</body> 
</html>

1. If the script is placed in the head element, the div element has not yet been loaded when the script is loaded, and "document.getelementbyid (...) will appear. Is null or not an object.
2, the above code in chrome normal branch, the output result is 5, but in IE output result is 0.
3. Note that you don't need to use [] to define data in js, otherwise you will make an error.


Related articles: