Nordax Nordax - 12 days ago 8
HTML Question

How to get the value of an attr jquery

I've dynamically created multiples divs and I randomly assigned an attribute id ,called mine-data with a value of 10, to some of them, now I'm creating a function that looks for divs with attribute 'mine-data' and returns true. but it doesn't work. I've looked at similar questions and none of the answers worked.
Any idea how to make it work?

function isattr() {
var attrb=$('.grid').attr('mine-data');
if(attrb==10) {
return true;
}
}

Answer

$('.grid') will return object contains all of element with class .grid. If you want to create a checking function, you need to pass each of it. please review this one

function isattr(elm) {
  var attrb = $(elm).attr('mine-data');
  //compare with string 10
  if (attrb === '10') {
    return true;
  }
  return false;
}

//get the array
var arrs = $('.grid').toArray();
//check for each element
arrs.forEach(function(elm) {
  // here we check each element and addEventListener      
  $(elm).on('click', function(e) {
     console.log(isattr(this));
  });
})
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<div class="grid" mine-data=10>ok</div>
<div class="grid" mine-data=10>ok</div>
<div class="grid" mine-data=9>not</div>
<div class="grid">not</div>
<div class="grid" mine-data=10>ok</div>