Как найти элемент по дата атрибуту 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.6k34 gold badges167 silver badges256 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,21117 gold badges76 silver badges135 bronze badges

answered Nov 9, 2012 at 23:32

Bryan Garaventa's user avatar

  1. Find a Data Attribute Using jQuery .find() Method
  2. Find a Data Attribute Using a CSS Attribute Selector
  3. Find a Data Attribute Using the .filter() Method

jQuery: Find Element With Data Attribute

To search for an element with a data attribute using jQuery, you can use the .find() method, the .filter() method, or a CSS attribute selector. This article teaches you how you can use them all using practical code examples.

Find a Data Attribute Using jQuery .find() Method

In jQuery, the .find() method allows you to search for an element on a web page using a CSS selector. Here, you can use it to find a data attribute if you write the right CSS selector.

From this, you can do what you want with elements that match the CSS selector. In the example below, we searched for data-name=Edison and changed its font size to 3em.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>01-jQuery-find-data-attr</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
	<main>
		<ul>
			<li data-name="Edison">Thomas Edison</li>
			<li data-name="Einstein">Albert Einstein</li>
			<li data-name="Rutherford">Ernest Rutherford</li>
		</ul>
	</main>
	<script>
		$(document).ready(function() {
			$("ul").find("[data-name='Edison']").css('font-size', '3em');
		});
    </script>
</body>
</html>

Output:

Find element with data attribute with jQuery find method

Find a Data Attribute Using a CSS Attribute Selector

You can find a data attribute using a CSS attribute selector. But there are two ways to do this, depending on your HTML markup.

In the first example below, the list items have data attributes. So, you can use a CSS descendant selector, which consists of a tag selector and a CSS attribute selector.

The result is a pinpoint match of the required element, and you can apply CSS styles afterward.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>02-jQuery-find-data-attr</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
	<style>
		body {
			font-family: "Trebuchet MS", Verdana, sans-serif;
			font-size: 1.2em;
		}
	</style>
</head>
<body>
	<main>
		<ul>
			<li data-iso="MRT">Mauritania</li>
			<li data-iso="LUX">Luxembourg</li>
			<li data-iso="HRV">Croatia</li>
		</ul>
	</main>
	<script>
		$(document).ready(function() {
			$("ul [data-iso='MRT'").css('color', 'magenta');
		});
    </script>
</body>
</html>

Output:

Find data by attribute using a CSS attribute selector

The second example below has a different HTML and jQuery code. First, the parent <ul> element has the data attribute in the HTML.

This means the previous selector in the last example will not work. To solve this, you can remove the space between the <ul> element and the CSS attribute selector.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>02_01-jQuery-find-data-attr</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
	<main>
		<ul data-viruses="computer-viruses">
			<li>Mydoom</li>
			<li>ILOVEYOU</li>
			<li>WannaCry</li>
		</ul>
	</main>
	<script>
		$(document).ready(function() {
			$("ul[data-viruses='computer-viruses']").css('font-style', 'italic');
		});
    </script>
</body>
</html>

Output:

Find data by attribute using a CSS attribute

Find a Data Attribute Using the .filter() Method

The .filter() method will match an HTML element using a CSS selector. With this, you can pass the CSS selector of an element and work with the result.

That’s what we’ve done in the code example below. Unlike previous examples, we add a CSS class using the jQuery .addClass() method.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>03-jQuery-find-data-attr</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
	<style>
		.style-chef {
			background-color: #1a1a1a;
			color: #ffffff;
			padding: 0.2em;
			width: 40%;
		}
	</style>
</head>
<body>
	<main>
		<ul>
			<li data-esolang="Befunge">Befunge</li>
			<li data-esolang="Chef">Chef</li>
			<li data-esolang="Whitespace">Whitespace</li>
		</ul>
	</main>
	<script>
		$(document).ready(function() {
			$("li").filter('[data-esolang="Chef"]').addClass('style-chef');
		});
    </script>
</body>
</html>

Output:

Find data by attribute using the jQuery filter method

For Single Test Input Div on page,
Firstly, get data attribute string and break into array with the help of split function.

attrName = 'data-party-registration-source-type-id';

dataArray = $('['+attrName+']').attr(attrName).split(",");

Then, trim array value to remove any white space and praseInt to convert character into int.

 trimmedDataArray = $.map(dataArray, function(value) {
  return parseInt(value.trim());
 });

testVal = 3;
isExist = $.inArray( testVal, trimmedDataArray );

If, «isExist» = -1 (not found)
Else, (found)

For Multiple Test Input Div on page,

Use above code in with each function

attrName = 'data-party-registration-source-type-id';
testValArray = [3,4,5,6];
$('['+attrName+']').each(function(index){
     dataArray = '';
     dataArray = $(this).attr(attrName).split(",");
      trimmedDataArray = $.map(dataArray, function(value) {
         return parseInt(value.trim()); // for words use, return value.trim();
      });

     testVal = testValArray[index];
     isExist = $.inArray( testVal, trimmedDataArray );
     //your code

});

Доброго времени суток
Как известно к атрибутам data-* можно обращаться через функцию jQuery data(‘foo’) и получить значение этого пользовательского атрибута.

<ul>
<li class="demo" data-id='1'>Пункт 1</li>
<li class="demo" data-id='2'>Пункт 2</li>
<li class="demo" data-id='3'>Пункт 3</li>
<li class="demo" data-id='4'>Пункт 4</li>
</ul>

то есть если повесить обработчик onclick на класс demo и вызвать в функции $(this).data(‘id’) он вернет нам значение этого атрибута, т.е. щелкнули на пункт 3, вернется 3
Но! Как добраться непосредственно по значению id к элементу li, то есть знаем что нам нужен li с id 2 как к нему обратиться? Нашёл способ
$('[data-id='+id+']')
но чувствую, что есть другой способ или функция, которая специально для этого создана


  • Вопрос задан

    более трёх лет назад

  • 78109 просмотров

Вполне нормальный селектор, только контекст добавить не мешало бы и использовать $.fn.children (если задача/разметка позволяет):

var $item = $('#dataset').children('[data-id="'+id+'"]');

ничего не нужно выдумывать. Обычный селектор по атрибуту. И работает он так же как и все остальные селекторы по скорости (если конечно вы не про ie7 какой-нибудь). Скорость работы селектора равноценна его специфичности. Скажем селектор #dataset [data-toggle] будет работать медленнее чем #dataset > [data-toggle] или же просто [data-toggle]. Селекторы все же с права на лево обрабатываются. И да, так мы жестко даем понять что мы должны добавить атрибут а не через метод $.fn.data назначить что-то.

Пригласить эксперта

А зачем вообще так делать? Что вам мешает добавить еще один класс в разметку и уже по нему обращаться. Это будет гораздо быстрее, чем через атрибут.

Опять таки есть нюанс. Дата атрибуты при изменении не меняют своего состояния в разметке. То есть, если у вас был элемент:
<li class="demo" data-id='1'>Пункт 1</li>,
затем его значение дата атрибута поменяли
$('demo').eq(0).data('id', 3),
то вы разметке он все также останется
<li class="demo" data-id='1'>Пункт 1</li>.
Это может привести к проблемам.

@dedik Ну как вариант вы всегда можете дописать свой селектор (особенно если не важна скорость :-) Думаю в вашем случае — вы легко можете себе это позволить.

jQuery.extend(jQuery.expr[':'], {  data: function (el,index,prop) {
    if (typeof(prop[3]!=undefined) && prop[3])
    {
        var attrs=prop[3].split('=');
        if ( $(el).attr('data-' + attrs[0]) && ( (attrs.length > 1 && $(el).attr('data-' + attrs[0])==attrs[1]) || attrs.length == 1 ) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return false;    
}});
console.log($(':data(id=5)'));

Только не забывайте делать селектор с контекстом, чтобы перебор был только в нужом месте, как писали выше, т.е.
$(':data(id=5)', DIV_WITH_IMAGES)


  • Показать ещё
    Загружается…

30 мая 2023, в 00:55

125000 руб./за проект

30 мая 2023, в 00:34

1000 руб./за проект

29 мая 2023, в 23:21

2000 руб./за проект

Минуточку внимания

Topic: JavaScript / jQueryPrev|Next

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.

Let’s check out the following example to understand how it works:

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Selecting Element by Data Attribute</title>
<style>
    ul li { 
        float: left;
        margin: 10px;
        list-style: none;
    }
    ul li img.selected{
        outline: 5px solid black;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("select").change(function(){
        // Get selected option value from dropdown
        var slide = $(this).children("option:selected").val();
        
        // Remove existing selected class from the image
        $(".slides img").removeClass("selected");
        
        // Select image based on its data-slide attribute value
        $('.slides img[data-slide=' + slide + ']').addClass("selected");
    });    
});
</script>
</head>
<body>
    <label>Slide:</label>
    <select>
        <option>select</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
    </select>
    <hr>
    <ul class="slides">
        <li>
            <img src="images/club.jpg" alt="Club" data-slide="1">
        </li>
        <li>
            <img src="images/diamond.jpg" alt="Diamond" data-slide="2">
        </li>
        <li>
            <img src="images/spade.jpg" alt="Spade" data-slide="3">
        </li>
        <li>
            <img src="images/heart.jpg" alt="Heart" data-slide="4">
        </li>
    </ul>
</body>
</html>


Related FAQ

Here are some more FAQ related to this topic:

  • How to get the data-id attribute of an element using jQuery
  • How to select an element by name in jQuery
  • How to check if an element exists in jQuery

Понравилась статья? Поделить с друзьями:
  • Как найти отчет какого то предприятия
  • Как составить буферную систему
  • Как найти угол поворота оси
  • Как найти как нарисовать животных
  • Как составить характеристику родителей детей