HierarchyRequestError: DOM Exception 3 when trying to insertbefore

ale picture ale · Mar 19, 2013 · Viewed 12k times · Source

While trying to insert option with insertbefore, I am getting this error. Uncaught Error: HierarchyRequestError: DOM Exception 3

var target = $('#divA option:selected').prev().first();
    var options = $('#divA option:selected');
    if (options.prev().text() == target.text()) {
        return;
    }
    options.insertBefore(target);

if options.length > 2 this error occurs, if it is 1 or 2 there is no problem. when multiple selection goes to top, all selected items will be disappeared. what is the problem? could you help me?

sample :http://jsfiddle.net/tHVsw/

Answer

undefined picture undefined · Mar 19, 2013

This error is thrown when insertion of an element to a specific point in the DOM is not allowed(ie. it is not possible), you can use an if statement for checking whether insertion is possible or not.

if ( !target.prev().length ) 
    target.parent().prepend(options);
else 
    target.before(options);

If the length of previous sibling of the target element is 0, prepend the element(s) to the parent element, otherwise insert it before the target element.

http://jsfiddle.net/fKx68/