Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to search for attributes that start with a certain string in HTML

Is there a way to find all the elements with attributes that start with a particular string?

I am using Mootools framework and this is what I have tried:

$$('*[data-media-*]');

But it just outputs all the elements in the page.

So is there a way to get all the elements in the page that have attributes that start with, data-media-?

like image 596
jnbdz Avatar asked Sep 18 '12 06:09

jnbdz


1 Answers

You can approximate something like this by iterating through the attributes for each element in the container, and seeing whether the attribute name matches a regex for what you are looking for:

For example, in this jsFiddle, I am looking for li elements with the data-media-tv and data-media-dvd properties.

You can tailor the regex to return only what you want to see. Want to only see elements that have a data-media-* (like in your question)? Here you go.


Keep in mind that this isn't exactly scalable. Because we are iterating through every single element on the page, and checking every single attribute (but returning early if found), this can and will probably be slow for large pages.

Limit this to ONLY the container you want to search, or only the elements you want to iterate through! If you run this against document.body, it will iterate through every single element in the page, I will not be responsible if your house burns down as a result. :)


Here it is function-ized:

function attrMatch(elements, regexp) {
    // Iterate through all passed-in elements, return matches
    var matches = elements.filter(function(li) {
    var numAttr = li.attributes.length;
    for(x=0;x<numAttr;x++) {
        var attr = li.attributes[x];
        return attr['name'].test(regexp);
    }
    });

    return matches;
};

In elements, only pass in the elements you want to check, possibly selected via $$. If you want to check all elements in a container element, replace elements with container and container.getChildren() in each instance of element, above.

like image 193
Julian H. Lam Avatar answered Sep 28 '22 00:09

Julian H. Lam