4

I need to select all elements, which have an attribute starting with a given prefix - note I am talking about the attribute name, not value. For example:

<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>

In the above HTML, I need to get all elements that have an attribute starting with data-abc- - that is, the div and the a.

How can I do that?

4 Answers 4

3

Here is my solutions - Fiddle. You have to create your own jquery selector.

jQuery.extend(jQuery.expr[':'], {
    attrStartsWith: function (el, _, b) {
        for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
            if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) {
                return true; 
            }
        }

        return false;
    }
});

//e.g:
$('a:attrStartsWith("data-abc")').html('hello');
$('div:attrStartsWith("data-abc")').html('hello');
Sign up to request clarification or add additional context in comments.

2 Comments

I had to use this recently. I found the answer here somewhere, but I couldn't find the source just now. If someone knows, let me know and I'll provide author the ownership!
This actually looks promising. So, to find all such elements, I'd use $('*:attrStartsWith("data-abc-")')
1

You can do it like this by ES6:

$('*').filter(function() {
  for (attr of this.attributes)
    if (attr.name.startsWith("data-abc"))
      return this;
});

Online demo (jsFiddle)

Comments

1
Array.from(document.querySelector('element').attributes).filter(x=>x.name.startsWith('attr-starts-with'))

Comments

0

I don't think we have jQuery selector with regex. However you can make use of this

Until you find a proper selector, here is a small workaround, that selects elements with matching attribute

var nodes = [];
$("body > *").each(function(){ //iterating over all nodes
  $(this.attributes).each(function(){
    console.log(this.nodeName);
    if(this.nodeName.indexOf("data-abc") > -1){
      nodes.push(this);
    }
  });
});

console.log(nodes.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>

1 Comment

Yeah, if no selector is available, manually traversing the DOM and checking attributes is the only option. However this is extremely inefficient. Your code only checks top level elements. I need to find elements everywhere in the DOM. And the DOM itself is very large in my case (over a million elements). That said, mostly likely, that's why jQuery is doing anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.