Question

I'm trying to customize a javascript autosuggest result display a bit, by showing an image next to every result. It works great, except in IE. This is the code I added:

var a = _b.DOM.cE("a", { href:"#" });
var pic = _b.DOM.cE("img",{src:"AutoSuggest/"+arr[i].id+".jpg",className:"float"}," ");
a.appendChild(pic);

Here's the _b.DOM.cE function:

if (typeof(_b.DOM) == "undefined")
    _b.DOM = {};

/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
    var ne = document.createElement( type );
    if (!ne)
            return 0;

    for (var a in attr)
            ne[a] = attr[a];
    var t = typeof(cont);
    if (t == "string" && !html)
            ne.appendChild( document.createTextNode(cont) );
    else if (t == "string" && html)
            ne.innerHTML = cont;
    else if (t == "object")
            ne.appendChild( cont );
    return ne;
};

IE gives the error "Unexpected call to method or property access", exactly as described here: JavaScript IE appendChild() - Unexpected call to method or property access One of the people that answered said that IE gives that error because of <img ...></img>, which I indeed see in the HTML my result creates. It should of course be <img ... />. So how can I fix this? Your help would be greatly appreciated!

Was it helpful?

Solution

Remove the ," " from the end of the img-creation line.

What your code is doing is attempting to do:

theImageElement.appendChild(document.createTextNode(" "));

While some browsers may allow and silently ignore this error, it is indeed an error and IE is strictly speaking correct to complain about it.

As an aside, HTML does not have self-closing tags. So <img></img> is indeed the "correct" HTML representation of an image element, however the <img> element is not allowed to have child nodes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top