Obtains all HTML elements in the DOM where an attribute name begins with a string

advertisements

I've stumbled upon a tricky one, that I haven't been able to find any references to (except one here on Stackoverflow, that was written quite inefficiently in Plain Old Javascript - where I would like it written in jQuery).

Problem

I need to retrieve all child-elements where the attribute-name (note: not the attribute-value) starts with a given string.

So if I have:

<a data-prefix-age="22">22</a>
<a data-prefix-weight="82">82</a>
<a href="#">meh</a>

My query would return a collection of two elements, which would be the first two with the data-prefix--prefix

Any ideas on how to write up this query?

I was going for something like:

$(document).find("[data-prefix-*]")

But of course that is not valid

Hopefully one of you has a more keen eye on how to resolve this.

Solution

(See accepted code example below)

There is apparently no direct way to query on partial attribute names. What you should do instead (this is just one possible solution) is

  1. select the smallest possible collection of elements you can
  2. iterate over them
  3. and then for each element iterate over the attributes of the element
  4. When you find a hit, add it to a collection
  5. then leave the loop and move on to the next element to be checked.

You should end up with an array containing the elements you need.

Hope it helps :)


Perhaps this will do the trick -

    // retrieve all elements within the `#form_id` container
    var $formElements = $("form#form_id > *");

    var selectedElements = [];
    // iterate over each element
    $formElements.each(function(index,elem){
        // store the JavaScript "attributes" property
        var elementAttr = $(this)[0].attributes;
        // iterate over each attribute
        $(elementAttr).each(function(attIndex,attr){
            // check the "nodeName" for the data prefix
            if (attr.nodeName.search('data-.*') !== -1){
               // we have found a matching element!
               if (selectedElements.length < 2){
                 selectedElements.push(elem);
                 break;
               }else{
                 if (selectedElements.length == 2){
                   break(2);
                 }
               }
            }
        });
    });

selectedElements will now hold the first two matching elements.

jsFiddle