What exactly can cause an "HIERARCHY_REQUEST_ERR: DOM Exception 3"-Error?

Viewed 79364

How exactly does it relate to jQuery? I know the library uses native javascript functions internally, but what exactly is it trying to do whenever such a problem appears?

15 Answers

It means you've tried to insert a DOM node into a place in the DOM tree where it cannot go. The most common place I see this is on Safari which doesn't allow the following:

document.appendChild(document.createElement('div'));

Generally, this is just a mistake where this was actually intended:

document.body.appendChild(document.createElement('div'));

Other causes seen in the wild (summarized from comments):

  • You are attempting to append a node to itself
  • You are attempting to append null to a node
  • You are attempting to append a node to a text node.
  • Your HTML is invalid (e.g. failing to close your target node)
  • The browser thinks the HTML you are attempting to append is XML (fix by adding <!doctype html> to your injected HTML, or specifying the content type when fetching via XHR)

This error can occur when you try to insert a node into the DOM which is invalid HTML, which can be something as subtle as an incorrect attribute, for example:

// <input> can have a 'type' attribute
var $input = $('<input/>').attr('type', 'text');
$holder.append($input);  // OK

// <div> CANNOT have a 'type' attribute
var $div = $('<div></div>').attr('type', 'text');
$holder.append($div);   // Error: HIERARCHY_REQUEST_ERR: DOM Exception 3

I got that error because I forgot to clone my element.

// creates an error
clone = $("#thing");
clone.appendTo("#somediv");

// does not
clone = $("#thing").clone();
clone.appendTo("#somediv");
Related