Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I find elements that contain a data-* attribute matching a prefix using jquery

I'm want to create a selector to find elements which have attributes starting with a string. At this point, I'm assuming this selector does not exist. Do I need to extend the selector capabilities? Extending jQuery’s selector capabilities by James Padolsey

I need to express something like the Attribute Contains Prefix Selector [name|="value"], but instead of matching "value", I need to match against the name of the attribute, and not the value of the attribute.

<tag data-plugin-option1="val1" data-plugin-option2="val2" />

I'd like to end up with a syntax like this: $('tag(:attr|="data-plugin")') which should find the element tag because it has at least one element that starts with data-plugin

like image 729
JJS Avatar asked Sep 29 '11 19:09

JJS


People also ask

How do you find the element based on a data attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How get data attribute value in jQuery?

You can use this jquery attr() syntax for get data-id attribute value. $("selector"). data("data-textval"); You can use this jquery attr() syntax for get data-textval attribute value.

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.

Which selects elements that have the specified attribute with a value beginning exactly with a given string?

attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.


1 Answers

Well, I guess I'm reading your question differently.

The way I read it, you want to create a custom selector that selects elements that have a given attribute name (or the start of that name).

If so, I think you'd need to iterate of the attributes collection for each element.

DEMO: http://jsfiddle.net/GgmM7/

$.extend($.expr[':'],{
    attrNameStart: function(el,i,props) {

        var hasAttribute = false;

        $.each( el.attributes, function(i,attr) {
            if( attr.name.indexOf( props[3] ) !== -1 ) {
                hasAttribute = true;
                return false;  // to halt the iteration
            }
        });

        return hasAttribute;
    }
});

$('img:attrNameStart(data-plugin)')
like image 76
user113716 Avatar answered Sep 29 '22 03:09

user113716