Reputation: 15197
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?
Upvotes: 14
Views: 10598
Reputation: 780889
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;
});
Upvotes: 0
Reputation: 29
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.
Upvotes: 1
Reputation: 1932
Try this
$().ready(function() {
var test=$('#div_test').data("foo-bar");
alert(test);
});
HTML:
<div data-foo-bar="hello" id="div_test"></div>
Upvotes: 0
Reputation: 298166
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/
Upvotes: 12
Reputation: 10830
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-bar
s, but ALL data-foo
s! 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.
Upvotes: 4
Reputation: 100
Try something like this
var element = $('div[data-foo-bar=hello]');
Upvotes: -7