0

I'm new to jQuery.. I have the following html div containing several links, each with several data attributes

<div class="image-gallery">
j = 0;  
    @foreach (var image in @Model.Images)
    {
        <a class="secondary-img" href="..." data-img-sq-nr="@j" data-colorID="@image.ColorId" ... >
        <img .../>
        </a>
        j++;
    }

</div>

In a jQuery script, I need to find the element with a particular data-colorID and get its data-img-sq-nr, I was trying something like this, but this obvisousy doesn't work

var seq = $('.image-gallery a[data-colorID='some-other-variable'].attr(data-img-sq-nr));

any help is much appreciated, thanks

1415926535
  • 45
  • 6
  • 1
    Possible duplicate of [jQuery how to find an element based on a data-attribute value?](https://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value) this should help – Budyn Sep 03 '18 at 15:05

2 Answers2

0

Does it have to be jQuery? This is so easy in native Javascript:

const fooValue = 'foo'
const div = document.querySelector(`[data-foo=${fooValue}]`);

console.log(div.dataset.bar);
<div data-foo="foo" data-bar="baz"></div>
<div data-foo="foo2" data-bar="baz2"></div>

jQuery is also very easy:

const fooValue='foo';

const div =  $('[data-foo=' + fooValue + ']')
console.log(div.data('bar'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-foo="foo" data-bar="baz"></div>
<div data-foo="foo2" data-bar="baz2"></div>
connexo
  • 53,704
  • 14
  • 91
  • 128
0

You're on the right track. There are just a few small syntax errors in your statement, that's all. Here's a working demo:

$(function() {
  var seq = $(".image-gallery a[data-colorID='A']").attr("data-img-sq-nr");
  console.log(seq);
  var seq2 = $(".image-gallery a[data-colorID='B']").attr("data-img-sq-nr");
  console.log(seq2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-gallery">
  <a class="secondary-img" href="#" data-img-sq-nr="0" data-colorID="A">Item 1</a>
  <br/>
  <a class="secondary-img" href="#" data-img-sq-nr="1" data-colorID="B">Item 2</a>
</div>
ADyson
  • 57,178
  • 14
  • 51
  • 63