Alex
Alex

Reputation: 1060

jQuery getelementsbyclassname equivalent

I have written a lot of JavaScript code using getElementsByClass name and now realised this is not supported in IE8 so am trying to swap them all for the jQuery equivalent.

My code runs without errors using

   div1.getElementsByClassName("div2");

however if I swap this line for

   $(".div1 .div2");

my code produces an error "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist."

What is the difference between the JavaScript code and jQuery code that could make the code behave differently?

Upvotes: 2

Views: 7891

Answers (2)

Dagg Nabbit
Dagg Nabbit

Reputation: 76766

If you've already written code using getElementsByClassName, you might be better off using a shim or polyfill so you don't have to rewrite existing code.

Unfortunately, most of the stuff out there only supplies document.getElementsByClassName, so if you're using it from other elements, you'll have to roll your own you can try this one I wrote a while back.

// getElementsByClassName polyfill
(function(){
    if (document.getElementsByClassName)
        return;
    if (!window.Element)
        throw "Can't polyfill getElementsByClassName";

    function gEBCN(className) {
        var all = this.getElementsByTagName("*"),
            rex = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"),
            out = [],
            element, i;
        for (i = all.length; i--;) {
            element = all[i];
            if (element.className.match(rex))
                out.unshift(element);
        }
        return out;
    }

    var el = window.Element.prototype;
    var doc = document.constructor.prototype;
    el.getElementsByClassName = doc.getElementsByClassName = gEBCN;
}());

This script checks if document.getElementsByClassName exists, and if it doesn't, it creates document.getElementsByClassName and Element.prototype.getElementsByClassName with equivalent functionality. Since all HTML elements have Element.prototype in their prototype chain, you'll be able to call .getElementsByClassName on any element, just as you can in any browser that has native support for the function. In other words, you can just drop this code at the top of your file or put it a separate file and include it, and then your current scripts should work in old IE and any other browsers that don't support .getElementsByClassName.

Upvotes: 2

Bram Vanroy
Bram Vanroy

Reputation: 28505

Note that jQuery 2.x does not support IE6/7/8. This might be the problem. Instead, use the 1.x branch (for example version [1.10.2]), which still supports those browsers.

When using a 1.x version of jQuery, the following should be the correct selector for what you want.

$(".div1 .div2") //or:
$(".div1").find(".div2") // or, if .div2 is a direct descendant:
$(".div1 > .div2")

Upvotes: 1

Related Questions