EvilDr
EvilDr

Reputation: 9610

Find all elements that have a data item property, regardless of element type or data item value

So far I can only find solutions that search for elements containing a specific data-item value. Instead I need to find any element (currently input or select) that have a data item called data-showsubmenutypes that also has any value.

So far my solution is to use two separate searches (which does work):

$(".ContactForm fieldset input[data-showsubmenutypes], .ContactForm fieldset select[data-showsubmenutypes]").each(function () {
    // myArray.push($(this).data("showsubmenutypes"));
});

However, it's long-winded and difficult to read. Is there any way to simplify the above?

I've tried dozens of attempts which all return undefined errors, such as:

$(".ContactForm fieldset").data("showsubmenutypes").each(function () {

$(".ContactForm fieldset *").data("showsubmenutypes").each(function () {

$(".ContactForm fieldset [data-showsubmenutypes]").each(function () {

Upvotes: 0

Views: 174

Answers (2)

epascarello
epascarello

Reputation: 207537

You should be able to just use the attribute selector. I also see it appears you are trying to get all the values, using map will make your life easier.

const types = $('.ContactForm fieldset [data-showsubmenutypes]').map(function(){ 
  return $(this).data('showsubmenutypes')
}).get()
console.log(types)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="ContactForm">
  <fieldset>
    <select data-showsubmenutypes="foo"></select>
    <input data-showsubmenutypes="bar" />
  </fieldset>
</form>

Upvotes: 1

Keith
Keith

Reputation: 4137

Have you tried doing a find?

var test = $('div').find('[data-list]');
$(test).each(function(i, value){
   console.log(value);
})

https://jsfiddle.net/bykse6xp/

Upvotes: 0

Related Questions