jQuery selector for elements with attribute starti

2019-03-31 11:40发布

问题:

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?

回答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)



回答2:

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>



回答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');