jQuery attribute name contains

2019-01-04 14:52发布

I'm trying to target attributes names which contains a certain word & not in the kind of way you're thinking.

Lets say I have:

<div data-foo-bar="hello"></div>

How can I target elements which have 'data-foo' in the attribute name?

6条回答
该账号已被封号
2楼-- · 2019-01-04 14:57

This is just an alternative solution. If you can ensure the attribute's name you're looking for is not present in the element text, what you could do is getting the outerHtml value of the element and then make a substring search:

$("elementsToCheck").each(function () {
    var elemHtml = $('<div>').append($(this).clone()).html(); //clone to get the outerHTML
    if (elemHtml.indexOf("attributeName") >= 0) {
        // current element contains the attribute with name "attributeName"
    }
});

Hope this helps.

查看更多
疯言疯语
3楼-- · 2019-01-04 14:59

Try something like this

var element = $('div[data-foo-bar=hello]')​;
查看更多
不美不萌又怎样
4楼-- · 2019-01-04 15:02

Try this

$().ready(function() {  
  var test=$('#div_test').data("foo-bar");
  alert(test);
});

HTML:

<div data-foo-bar="hello" id="div_test"></div>
查看更多
疯言疯语
5楼-- · 2019-01-04 15:06

I'm not sure you can do that. I've had a peek at the API and you only seem to be able to do deeper partial matching on the value, not the attribute name itself.

I'm going to give you the potentially frustrating advice of, "don't do this". ;-) In essence, what you're after is a bunch of divs that match a more general category. Not just data-foo-bars, but ALL data-foos! Why not just give all data-foos a classname that you can select from, or a separate attribute like data-foo="true"?

In other words, rather than sticking strictly to the question as asked, I'd be curious to know what the use case is so that maybe a lateral move in thinking can solve your problem just as effectively. Many ways to skin a cat and all that.

查看更多
叼着烟拽天下
6楼-- · 2019-01-04 15:15

Use .data() to get all the data attributes of an element, and then use .filter to get the elements that have data-validation* attributes.

var validated_elements = $("p").filter(function() {
    var found = false;
    $.each($(this).data(function(key) {
        if (key.match(/^data-validation/)) {
            found = true;
            return false;
        }
    }
    return found;
});
查看更多
叛逆
7楼-- · 2019-01-04 15:18

I don't think you can target attribute names the same way you target attribute values. You can, however, use .filter() to do this somewhat efficiently:

$('div').filter(function() {
  for (var property in $(this).data()) {
    if (property.indexOf('fooBar') == 0) {
      return true;
    }
  }

  return false;
});​

Notice that data-foo-bar has been converted to fooBar.

Demo: http://jsfiddle.net/Tyj49/3/

查看更多
登录 后发表回答