View Single Post
May 24th, 2009
0

Re: Parsing an HTML String

getElementById() only works with document. To parse your HTML can use childNodes;

Modifying your code all little bit:

javascript Syntax (Toggle Plain Text)
  1. function parseHTML(html) {
  2. var root = document.createElement("div");
  3. root.innerHTML = html;
  4.  
  5. // Get all child nodes of root div
  6. var allChilds = root.childNodes;
  7. // Loop through all the child nodes and check for id = 'head'
  8. for(var i = 0; i < allChilds.length; i++) {
  9. // if id == 'head', you get your element
  10. if (allChilds[i].id && allChilds[i].id == "head") {
  11. // Remove it from root
  12. root.removeChild(allChilds[i]);
  13. }
  14. }
  15. document.body.innerHTML = root.innerHTML;
  16. }
Reputation Points: 83
Solved Threads: 61
Posting Pro in Training
Luckychap is offline Offline
442 posts
since Aug 2006