The key is
- The string you assign to the variable "el.innerHTML" can't contain double quotes character. You can convert the double quotes character to a single quote character.
- If you assign the html string inside a textarea, it will convert < character to < string and convert > character to > string automatically. So you have to convert these characters back to <,> character.
- You have to convert the html string to a single line. If the html string has multiple lines with a \n character.
<html>
<head>
<title>parse a html string in javascript</title>
</head>
<body>
<p>Click the button to test:</p>
<button onclick="myFunction()">Result</button>
</br>
<textarea style="width: 400px;height: 200px;"id="demo"><html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html></textarea>
<script>
function myFunction() {
var el = document.createElement( 'html' );
el.innerHTML =document.getElementById("demo").innerHTML.replace(/</g,'<').replace(/>/g,'>');
console.log(el.innerHTML);
document.getElementById("demo").innerHTML = el.getElementsByTagName( 'title' )[0].innerHTML;
}
</script>
</body>
</html>
Reference:
http://stackoverflow.com/questions/10585029/parse-a-html-string-with-js
Comments
Post a Comment