Как найти все элемент по атрибуту jquery

I’ve got the following scenario:

var el = 'li';

and there are 5 <li>‘s on the page each with a data-slide=number attribute (number being 1,2,3,4,5 respectively).

I now need to find the currently active slide number which is mapped to var current = $('ul').data(current); and is updated on each slide change.

So far my tries have been unsuccessful, trying to construct the selector that would match the current slide:

$('ul').find(el+[data-slide=+current+]);

does not match/return anything…

The reason I can’t hardcode the li part is that this is a user accessible variable that can be changed to a different element if required, so it may not always be an li.

Any ideas on what I’m missing?

Frédéric Hamidi's user avatar

asked Nov 16, 2010 at 5:11

Jannis's user avatar

2

You have to inject the value of current into an Attribute Equals selector:

$("ul").find(`[data-slide='${current}']`)

For older JavaScript environments (ES5 and earlier):

$("ul").find("[data-slide='" + current + "']"); 

answered Nov 16, 2010 at 6:30

Frédéric Hamidi's user avatar

Frédéric HamidiFrédéric Hamidi

257k41 gold badges484 silver badges478 bronze badges

3

When searching with [data-x=…], watch out, it doesn’t work with jQuery.data(..) setter:

$('<b data-x="1">'  ).is('[data-x=1]') // this works
> true

$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false

$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true

You can use this instead:

$.fn.filterByData = function(prop, val) {
    return this.filter(
        function() { return $(this).data(prop)==val; }
    );
}

$('<b>').data('x', 1).filterByData('x', 1).length
> 1

answered Mar 27, 2013 at 3:59

psycho brm's user avatar

psycho brmpsycho brm

7,4441 gold badge43 silver badges42 bronze badges

1

Without JQuery, ES6

document.querySelectorAll(`[data-slide='${CSS.escape(current)}']`);

I know the question is about JQuery, but readers may want a pure JS method.

Dmitriy Sintsov's user avatar

answered Jun 4, 2018 at 20:50

rap-2-h's user avatar

rap-2-hrap-2-h

29.5k34 gold badges167 silver badges255 bronze badges

I improved upon psycho brm’s filterByData extension to jQuery.

Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.

(function ($) {

    $.fn.filterByData = function (prop, val) {
        var $self = this;
        if (typeof val === 'undefined') {
            return $self.filter(
                function () { return typeof $(this).data(prop) !== 'undefined'; }
            );
        }
        return $self.filter(
            function () { return $(this).data(prop) == val; }
        );
    };

})(window.jQuery);

Usage:

$('<b>').data('x', 1).filterByData('x', 1).length    // output: 1
$('<b>').data('x', 1).filterByData('x').length       // output: 1

Or the fiddle: http://jsfiddle.net/PTqmE/46/

Community's user avatar

answered Mar 5, 2014 at 21:21

bPratik's user avatar

bPratikbPratik

6,8744 gold badges36 silver badges67 bronze badges

1

I have faced the same issue while fetching elements using jQuery and data-* attribute.

so for your reference the shortest code is here:

This is my HTML Code:

<section data-js="carousel"></section>
<section></section>
<section></section>
<section data-js="carousel"></section>

This is my jQuery selector:

$('section[data-js="carousel"]');
// this will return array of the section elements which has data-js="carousel" attribute.

Matthew R.'s user avatar

Matthew R.

4,3221 gold badge24 silver badges39 bronze badges

answered Oct 22, 2013 at 12:39

user1378423's user avatar

user1378423user1378423

5675 silver badges3 bronze badges

0

This selector $("ul [data-slide='" + current +"']"); will work for following structure:

<ul><li data-slide="item"></li></ul>  

While this $("ul[data-slide='" + current +"']"); will work for:

<ul data-slide="item"><li></li></ul>

answered Sep 30, 2016 at 15:08

Matas Vaitkevicius's user avatar

$("ul").find("li[data-slide='" + CSS.escape(current) + "']");

I hope this may work better

thanks

Dmitriy Sintsov's user avatar

answered Jul 12, 2016 at 6:26

Jomin George Paul's user avatar

Going back to his original question, about how to make this work without knowing the element type in advance, the following does this:

$(ContainerNode).find(el.nodeName + "[data-slide='" + current + "']");

Emil's user avatar

Emil

7,20117 gold badges76 silver badges134 bronze badges

answered Nov 9, 2012 at 23:32

Bryan Garaventa's user avatar

Соответствует всем элементам с атрибутом attribute равным value. Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

Соответствует всем элементам, у которых значение атрибута attribute заканчивается на value. Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

Соответствует всем элементам, которые имеют атрибут attributeName. При этом, не важно, какие им заданы значения.

Соответствует всем элементам, у которых значение атрибута attribute начинается с value. Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

Соответствует элементам, удовлетворяющим всем заданным условиям на атрибуты (first, second, …).

Соответствует всем элементам, у которых значение атрибута attribute не равно value. Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

Соответствует всем элементам, у которых значение атрибута attribute содержит value. Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

Соответствует всем элементам, с атрибутом attribute содержащим префикс value, т.е. либо полностью совпадает с value, либо начинается со строки value- (наличие знака переноса существенно). Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

Соответствует всем элементам с атрибутом attribute, содержащим слово value (именно слово, а не просто подстроку. То есть вхождение value должно содержать с обоих сторон разделители: пробелы или начало/конец строки). Если value состоит из нескольких слов, между которыми есть пробелы, то нужно заключать value в кавычки. Если value не содержит пробелов — кавычки не обязательны.

The most basic concept of jQuery is to “select some elements and do something with them.” jQuery supports most CSS3 selectors, as well as some non-standard selectors. For a complete selector reference, visit the Selectors documentation on api.jquery.com.

link Selecting Elements by ID

1

$( "#myId" ); // Note IDs must be unique per page.

link Selecting Elements by Class Name

link Selecting Elements by Attribute

1

$( "input[name='first_name']" );

link Selecting Elements by Compound CSS Selector

1

$( "#contents ul.people li" );

link Selecting Elements with a Comma-separated List of Selectors

1

$( "div.myClass, ul.people" );

link Pseudo-Selectors

1

2

3

4

5

6

7

8

9

10

11

12

// Select all input-like elements in a form (more on this below).

// All except the first three divs.

// All currently animated divs.

Note: When using the :visible and :hidden pseudo-selectors, jQuery tests the actual visibility of the element, not its CSS visibility or display properties. jQuery looks to see if the element’s physical height and width on the page are both greater than zero.

However, this test doesn’t work with <tr> elements. In the case of <tr> jQuery does check the CSS display property, and considers an element hidden if its display property is set to none.

Elements that have not been added to the DOM will always be considered hidden, even if the CSS that would affect them would render them visible. See the Manipulating Elements section to learn how to create and add elements to the DOM.

link Choosing Selectors

Choosing good selectors is one way to improve JavaScript’s performance. Too much specificity can be a bad thing. A selector such as #myTable thead tr th.special is overkill if a selector such as #myTable th.special will get the job done.

link Does My Selection Contain Any Elements?

Once you’ve made a selection, you’ll often want to know whether you have anything to work with. A common mistake is to use:

This won’t work. When a selection is made using $(), an object is always returned, and objects always evaluate to true. Even if the selection doesn’t contain any elements, the code inside the if statement will still run.

The best way to determine if there are any elements is to test the selection’s .length property, which tells you how many elements were selected. If the answer is 0, the .length property will evaluate to false when used as a boolean value:

1

2

3

4

// Testing whether a selection contains elements.

if ( $( "div.foo" ).length ) {

link Saving Selections

jQuery doesn’t cache elements for you. If you’ve made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.

Once the selection is stored in a variable, you can call jQuery methods on the variable just like you would have called them on the original selection.

A selection only fetches the elements that are on the page at the time the selection is made. If elements are added to the page later, you’ll have to repeat the selection or otherwise add them to the selection stored in the variable. Stored selections don’t magically update when the DOM changes.

link Refining & Filtering Selections

Sometimes the selection contains more than what you’re after. jQuery offers several methods for refining and filtering selections.

1

2

3

4

5

6

$( "div.foo" ).has( "p" ); // div.foo elements that contain <p> tags

$( "h1" ).not( ".bar" ); // h1 elements that don't have a class of bar

$( "ul li" ).filter( ".current" ); // unordered list items with class of current

$( "ul li" ).first(); // just the first unordered list item

$( "ul li" ).eq( 5 ); // the sixth

link Selecting Form Elements

jQuery offers several pseudo-selectors that help find elements in forms. These are especially helpful because it can be difficult to distinguish between form elements based on their state or type using standard CSS selectors.

link :checked

Not to be confused with :checkbox, :checked targets checked checkboxes, but keep in mind that this selector works also for checked radio buttons, and <select> elements (for <select> elements only, use the :selected selector):

The :checked pseudo-selector works when used with checkboxes, radio buttons and selects.

link :disabled

Using the :disabled pseudo-selector targets any <input> elements with the disabled attribute:

In order to get the best performance using :disabled, first select elements with a standard jQuery selector, then use .filter( ":disabled" ), or precede the pseudo-selector with a tag name or some other selector.

link :enabled

Basically the inverse of the :disabled pseudo-selector, the :enabled pseudo-selector targets any elements that do not have a disabled attribute:

In order to get the best performance using :enabled, first select elements with a standard jQuery selector, then use .filter( ":enabled" ), or precede the pseudo-selector with a tag name or some other selector.

link :input

Using the :input selector selects all <input>, <textarea>, <select>, and <button> elements:

link :selected

Using the :selected pseudo-selector targets any selected items in <option> elements:

In order to get the best performance using :selected, first select elements with a standard jQuery selector, then use .filter( ":selected" ), or precede the pseudo-selector with a tag name or some other selector.

link Selecting by type

jQuery provides pseudo selectors to select form-specific elements according to their type:

  • :password
  • :reset
  • :radio
  • :text
  • :submit
  • :checkbox
  • :button
  • :image
  • :file

For all of these there are side notes about performance, so be sure to check out the API docs for more in-depth information.

Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

Selects elements that have the specified attribute with a value containing a given substring.

Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

Selects elements that have the specified attribute with a value exactly equal to a certain value.

Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value.

Selects elements that have the specified attribute with a value beginning exactly with a given string.

Selects elements that have the specified attribute, with any value.

Matches elements that match all of the specified attribute filters.

I want to find all the elements on my page that have a ‘name’ attribute containing ‘x’ or ‘y’ and add a certain class to those elements.

So, the logic I’m looking to apply is

If anything has ‘x’ or ‘y’ in the name attribute then add .yepItHasXorY

It seems like a simple thing. I understand how to search based on an ID or Class but not the name attribute…

Nick Craver's user avatar

Nick Craver

621k136 gold badges1294 silver badges1155 bronze badges

asked Aug 3, 2010 at 18:48

Ofeargall's user avatar

You can use an attribute-contains selector, like this:

$("[name*=x], [name*=y]").addClass('yepItHasXorY');

Though, I would add an element type, on there or maybe :input to you’re only looking at elements you care about (otherwise it’s a much more expensive selector).

answered Aug 3, 2010 at 18:49

Nick Craver's user avatar

Nick CraverNick Craver

621k136 gold badges1294 silver badges1155 bronze badges

4

Добавить комментарий