jlee jlee - 3 months ago 7
HTML Question

Get each value of a custom attribute in a table

I'm trying to find a jQuery statement that will return an array containing each row's "key" value. Here is an example of one of my rows:

<tr id="sysconfig2" class="ConfigRow" key="exampleKey" val="true" dispval="true" dontencrypt="false" lastmodified="8/26/2016 10:14:08 PM"></tr>


Here is what I tried, however it returns 0 values.

$('#ConfigRow').each.attr("key");


I know it is probably a very simple statement, but I haven't been able to find any results in my search.

Thank you!

Answer

A couple of things.

  1. You are trying to get an element with an ID of ConfigRow using jQuery. You looks like that was a simple mistake, and you should be trying to get the elements with a className. $('.ConfigRow')
  2. In this case, you probably want to use map as it takes an existing array of elements or whatever, and returns a modified value.

var keys = $.map($('.ConfigRow').toArray(), function(el) {
  return $(el).attr('key')
});

console.log(keys);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr id="sysconfig2" class="ConfigRow" key="exampleKey" val="true" dispval="true" dontencrypt="false" lastmodified="8/26/2016 10:14:08 PM"></tr>
</table>