How to select special attributes (prefix: name = "")?

how to select custom attributes like "user: name" or "city: id" using jQuery?

<div user:name="Ropstah"></div>
<span city:id="4"></div>

Javascript

//this works:
alert($('div').attr("user:name"));  // alerts 'Ropstah'

//this doesn't work:
alert($('div[user:name]').attr("user:name"));    //error
alert($('div[user\\:name]').attr("user:name"));    //error even with special character escaping...
+3
source share
3 answers

This is a bug in jQuery .

You have two options:

  • Get rid of :and using "non-standard" attributes (to be honest, this is not a big deal).
  • Get more details or use the plugin to get functionality anyway:

Initially, you may need the following:

$('div').filter(function() {
    return $(this).attr('user:name') !== undefined;
}).whateverElse();

, jQuery [], , . , , , , jQuery - :

$.fn.hasattr = function(attr) {
    return this.filter(function() {
        return $(this).attr(attr) !== undefined;
    });
};

:

$('div').hasattr('user:name').whateverElse();

, , -, :

$.fn.cmpattr = function(attr, value) {
    return this.filter(function() {
        return $(this).attr(attr) == value;
    });
};

:

$('div').cmpattr('user:name', 'Ropstah').whateverElse();
+4

:

jQuery.expr.match.ATTR = /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+|\w+:\w+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/;
//                                                          ^^^^^^^^

. , , , .

, jQuery ... , , , .:)

+3

( .. , ) :

<div nonstandard="harmless" />

$("div[nonstandard='harmless']")

. .

+2
source

Source: https://habr.com/ru/post/1710411/


All Articles