Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an existing or upcoming CSS3 selector for matching substrings of attribute names?

You can do [foo^="bar"] to match nodes which have the attribute foo with value starting with bar.

Is there a way to match nodes with an attribute name starting with a particular string? The use case of this is to match all nodes with a data-* attribute.

Edit: the reason I'm trying this is to avoid iterating over all the nodes looking for these attributes (for performance reasons). I'd be using querySelectorAll and its Sizzle polyfill for older browsers.

like image 775
jli Avatar asked May 23 '13 22:05

jli


People also ask

What is an attribute selector?

The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.

What is the CSS selector for an anchor tag containing the title attribute?

The [attribute~=value] selector is used to select elements with an attribute value containing a specified word.

What is the name of the selector that allows you to select one or more elements based on their order in an HTML document?

The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.


2 Answers

One way is using .filter() method:

$('element').filter(function() {
    return $.grep(this.attributes, function(value) {
       return value.nodeName.indexOf('data') === 0;
    }).length;
});

http://jsfiddle.net/QACsw/

like image 142
undefined Avatar answered Oct 05 '22 20:10

undefined


It may be a little overkill, but you could write a custom selector:

$.expr[':'].attr = function (elem, index, regex_str) {
    var regex = new RegExp(regex_str[3]);

    for (var i = 0; i < elem.attributes.length; i++) {
        if (elem.attributes[i].name.match(regex)) {
            return true;
        }
    }

    return false;
};

Demo: http://jsfiddle.net/LBHwr/

So in your case, you'd do:

$('div:attr(^data)') // starts with
$('div:attr(foo$)')  // ends with

It's somewhat similar to the regular attribute selector syntax.

like image 29
Blender Avatar answered Oct 05 '22 19:10

Blender