jQuery - How to select value by attribute name starts with
Asked Answered
E

4

17

I want to select attribute value by giving attribute name (only starts with) For instance if we have html tag

<div class = "slide"  data-confirmID = "46" confirmID = "54"/>

I want to select the value from the attribute starts with data-

Thanks in advance for the help.

Encrimson answered 30/10, 2014 at 15:42 Comment(5)
What if you have multiple attributes that start with data-? Which value should you get?Dubbing
jQuery has a starts with selector: api.jquery.com/attribute-starts-with-selectorExtend
In my scenario i have only one.. so if I could select attribute name starting with 'data-', that should doEncrimson
@Extend That's for finding the elements with a data- attribute. He wants to find the value of the attribute, not use it as a selector.Maudmaude
@Extend - I actually wanted to select based on attribute name something like $('div').attr('data-*');Encrimson
L
25

If you want all data-* attributes, you can iterate through jq data object:

$('.slide').each(function(){
    for(data in $(this).data())
        console.log(data); // returns confirmID so element as an attribute `data-confirmID`
});

But this data object can contains other keys which aren't attribute, setted for example by some plugins.

EDIT

To get all kinds of attribute to "starts with", you can customize your own jQuery selector:

jQuery.extend(jQuery.expr[':'], {
    attrStartsWith: function (el, _, b) {
        for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
            if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) {
                return true; 
            }
        }
        
        return false;
    }
});

//e.g:
$('.slide:attrStartsWith("data-")').css('color', 'red');
$('.slide:attrStartsWith("conf")').css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="slide" data-confirmID="46" data-testID="666">1</div>
<div class="slide" confirmID="54" >2</div>

If on the opposite side, you want to check for attribute ends with specific string, you can use:

jQuery.extend(jQuery.expr[':'], {
    attrEndsWith: function (el, _, b) {
        for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
          var att = atts[i].nodeName.toLowerCase(),
              str = b[3].toLowerCase();
            if(att.length >= str.length && att.substr(att.length - str.length) === str) {
                return true; 
            }
        }
        
        return false;
    }
});

$('.slide:attrEndsWith("testID")').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="slide" data-confirmID="46" data-testID="666">1</div>
<div class="slide" confirmID="54" >2</div>
Lindbergh answered 30/10, 2014 at 15:47 Comment(3)
@A.Wolff Can't we access other attributes which not start from "data" ?Mauromaurois
@NishanSenevirathna Sure, you need to firstly get all attributes and then apply your logic, e.g to get attributes see: #2049220Lindbergh
@NishanSenevirathna Updated answer with custom selectorLindbergh
E
3

You could do it as a jQuery plugin. I'm not convinced its the right way to go about it but here's an example:

(function($) {
    $.fn.attrBegins = function(s) {
        var matched = "";
        this.each(function(index) {
            $.each(this.attributes, function( index, attr ) {
                if(attr.name.indexOf(s)===0){
                   matched =  attr.value
                }
            });
        });
        return matched;
    };
})(jQuery);

//example use
var val = $('div').attrBegins('data-');
alert(val);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="slide" data-confirmID="46" confirmID="54" />
Extend answered 30/10, 2014 at 16:28 Comment(0)
F
2

@Moob aproximation to jQuery attrBegins plugin, returns the attribute name (a string), when are matches... of a single element (ignoring multiple matches). I addapted the code to return a JQuery Collection with the matching elements.

Here is the code:

(function($) {
    $.fn.attrBegins = function(s) {
        var matched = [];
        this.each(function(index) {
            var elem = this;
            $.each(this.attributes, function( index, attr ) {
                if(attr.name.indexOf(s)===0){
                   matched.push(elem);
                }
            });
        });
        return $( matched );
    };
})(jQuery);

USAGE EXAMPLE...

HTML :

<div>
    <div data-pet-dog></div>
    <div data-pet-cat></div>
</div>

Javascript :

 var foo = $("div").attrBegins("data-pet");
// results into... foo = [ <div data-pet-dog></div> , <div data-pet-cat></div> ]

NOTE: To prevent performance issues when selecting elements wich have an attribute name that starts with a custom string using attrBegins, is recomended to narrow as much as possible the original selector, to reduce the collection of elements to iterate. attrBegins just filters the preselected elements collection, it does not explore the child elements of provided set of items.

Frambesia answered 13/5, 2016 at 7:19 Comment(0)
M
0

Attributes are properties of the element, so you can use a for-in loop

for (var prop in element) {
    if (prop.indexOf('data-') == 0) {
        var val = element[prop];
        break;
    }
}
Maudmaude answered 30/10, 2014 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.