2

I am looking for a method like document.getElementsByClassName(), but just for attributes, that would also mean that document.getElementsByAttributeValue("class", "testclass") would have the same output as document.getElementsByClassName("testclass").

It is not that easy since you cannot just add a function like this

document.getElementsByAttributeValue = function(){....};

because it has to work for document.getElementById("foo").getElementsByAttributeValue(...) as well.

Needless to say, that I don't want a JQuery solution because there is no need for a giant library for just one function.

Friedrich
  • 2,211
  • 20
  • 42

2 Answers2

2

The function I created and the implementation looks like this:

Node.prototype.getElementsByAttributeValue = function(attribute, value){
    var dom = this.all || this.getElementsByTagName("*");
    var match = new Array();
    for (var i in dom) {
        if ((typeof dom[i]) === "object"){
            if (dom[i].getAttribute(attribute) === value){
                match.push(dom[i]);
            }
        }
    }
    return match;
};

I wanted the function to work within every html element and in the html document as well, so I added the function to the parent class of all html subclasses, the Node class.

There is a nice visualisation of JavaScript objects.

With this.all || this.getElementsByTagName("*") I took all the html elements within the object which called the function. Then I looped through all the elements I took and checked if they had the right attribute values and if they had, I pushed them into the match array

Friedrich
  • 2,211
  • 20
  • 42
  • 4
    No need. You could just do `document.querySelectorAll("*[foo='bar']")` or as a substitute for `getElementsByClassName`, it would be `document.querySelectorAll(".some_class")`. –  Sep 27 '14 at 13:50
-4

You can use JQuery to easily get all the elements with a particular class as follows:

$('[class~="d1"]')

This will select the elements with class containing d1

Check Demo

For more: Read JQuery selector

Rajesh Paul
  • 6,793
  • 6
  • 40
  • 57