2

Here's the parseFunction

Ajax:
{
    ParseHTML: function(aHTMLString)
    {
        var html = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html", null),
        body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
        html.documentElement.appendChild(body);

        body.appendChild(Components.classes["@mozilla.org/feed-unescapehtml;1"]
            .getService(Components.interfaces.nsIScriptableUnescapeHTML)
            .parseFragment(aHTMLString, false, null, body));

        return body;
    }
}

Here I'm trying to use the parse in a http response (to sanatize the code):

var newdoc = Ajax.ParseHTML(o.responseText);

But, when I try to use:

newdoc.getElementById('teste');

It returns me the error: TypeError: newdoc.getElementById is not a function

Am I doing somthing wrong? It has something to do with documentType or something?

Also, this function removes all href="" attributes in a tags for example, maybe the problems are related ...

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
StiveKnx
  • 320
  • 4
  • 14

1 Answers1

2

getElementById is only defined on the document object, because an ID has to be unique in a document. For this reason, it did not make sense to define getElementById on an element object.

The following methods will work:

newdoc.querySelector('#teste');
newdoc.ownerDocument.getElementById('teste');

As for creating a document, you might be interested in the DOMParser, or want to use document.implementation.createHTMLDocument (with HTML).

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Cool, it solved the getelementById problem... I just replaced the return value to return body.ownerDocument. – StiveKnx Mar 08 '12 at 14:28
  • 1
    @StiveKnx If you want to return the document, just use `return html;`. This variable is equivalent to `body.ownerDocument`. – Rob W Mar 08 '12 at 14:35
  • this solved the problem with DOM, but still, keeps removing all href= atributes from `a` elements, any ideia why? – StiveKnx Mar 08 '12 at 16:57
  • @StiveKnx MDN's documentation for `nsIScriptableUnescapeHTML` might be outdated ([last notable edit 5+ years ago](https://developer.mozilla.org/index.php?title=en/XPCOM_Interface_Reference/nsIScriptableUnescapeHTML&action=history)), marked as outdated at [this page](https://developer.mozilla.org/User:trevorh/Interface_documentation_status). If you just want to parse a string in HTML, I recommend to have a look at the [linked answer](http://stackoverflow.com/a/9251106/938089?javascript-domparser-access-innerhtml-and-other-properties). – Rob W Mar 08 '12 at 17:59
  • Thanks, I'm using DOMParser Now, no problems or bugs for now, solved both problems! I tried first with nsIScriptableUnescapeHTML cause mozilla addons review told me to use it in my requests, so. Thanks – StiveKnx Mar 08 '12 at 18:32