Take custom attribute value "data-attribute" within a loop

Asked

Viewed 1,874 times

3

I want to select all custom attributes and do a validation with them, but I don’t know how I can get the "attr" value inside a loop, since they are the ones being iterated.

HTML example:

<input type="text" data-selected="teste" value="fulano" name="nome">
<input type="text" data-selected="teste2" value="de tal" name="sobrenome">

Example:

$('[data-selected]').each(function(){

       alert( $(this).attr() ); // -> teste / teste2
});

2 answers

4


You can make use of the API dataset(see support in "Can I use") to obtain the data-Attributes of a specific element:

[...document.querySelectorAll('[data-selected]')].map(element => {
  alert(element.dataset.selected)
})
<div data-selected="teste"></div>
<div data-selected="teste2"></div>

If you really need to use jQuery, there is the function data() which can be used by specifying the attribute name:

$(function(){
  $('[data-selected]').each(function(){
       alert( $(this).data('selected') );
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div data-selected="teste"></div>
<div data-selected="teste2"></div>

1

1) The selector it must be so: input[data-selected]. What’s going fetch the inputs that have the attribute data-Selected defined.

Source: jQuery API - Has Attribute Selector

2) To receive the value of the attribute, must inform it in the method .attr(), as suggested by the documentation of jQuery. So it should stay like this: $(this).attr('data-selected');.

Source: API jQuery - . attr()

Finally, your code would look like this:

$('input[data-selected]').each(function(){
    alert( $(this).attr('data-selected') ); // -> teste / teste2
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" data-selected="teste" value="fulano" name="nome">
<input type="text" data-selected="teste2" value="de tal" name="sobrenome">

  • 1

    An explanation of the answer would be most welcome! ;)

  • Thanks for the reply, but it is not limited only to input, can be select etc too

  • Logical. Just enter the target element in the jQuery! @Articunol selector!

  • Why not just $(['data-Selected'])?

  • It works too. But when you set the selector on us input prevents seeking other "possible elements" that may not be desired...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.