Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery attribute name contains

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?

like image 860
daryl Avatar asked Mar 03 '12 05:03

daryl


People also ask

How do you check if an element has an attribute in jQuery?

Using jQuery The idea is to use the . attr() method, which returns the attribute's value for an element if it is present and returns undefined if the attribute doesn't exist.

How add contains in jQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

How do you use getAttribute?

How it works: First, select the link element with the id js using the querySelector() method. Second, get the target attribute of the link by calling the getAttribute() of the selected link element. Third, show the value of the target on the Console window.

What is id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


1 Answers

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/

like image 142
Blender Avatar answered Nov 08 '22 11:11

Blender