0

How to use a variable instead of a table id?

For example, I want to replace the id #myTable with the variable table.

function findFruitColor(table, fruit) {


  let colKey = $("#myTable th:contains('Fruit')").index();
  let colVal = $("#myTable th:contains('Color')").index();

  $('#myTable tr td:nth-child(' + (colKey + 1) + ')').each(function() {

    if ($(this).text() === fruit) {
      color = $(this).siblings('td').addBack().eq(colVal).text();
      return false;
    }

  })


  // Display the color that was found 
  if (typeof color !== 'undefined') {
    console.log("The color for " + fruit + " is " + color);
  }


}

// Call the function
findFruitColor("#myTable", "apple");
th {
  font-weight: bold;
  width: 11em;
  text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="myTable">
  <tr>
    <th>Fruit</th>
    <th>Color</th>
  </tr>
  <tr>
    <td>apple</td>
    <td>red</td>
  </tr>
  <tr>
    <td>banana</td>
    <td>yellow</td>
  </tr>

View on jsFiddle

  • 1
    `$(table).find("tr ...")...` (also, provided that `table` is an id in string format, you can always do `$(table + " th ...")` but that's not good practice) –  Apr 16 '20 at 22:31
  • Does this answer your question? [How to use JavaScript variables in jQuery selectors?](https://stackoverflow.com/questions/5891840/how-to-use-javascript-variables-in-jquery-selectors) –  Apr 16 '20 at 22:49
  • @ChrisG Thanks but not quite. Your comment and the answer were both clearer. Maybe this question was specific to the find() method. For example, going from a hardcoded tableID—$("#id tr...")—to variable as seen here—$(table).find("tr...") requires us to add .find().That was the missing piece. –  Apr 16 '20 at 23:20

1 Answers1

2

The modern way

Use template literals:

let colKey = $(`${table} th:contains('Fruit')`).index();

Template literals save you alot of headache regarding the escaping of quotation characters. Find the browser support for this here.

The old way (which you're already using in your code example):

Use string concatenation:

let colKey = $(table + " th:contains('Fruit')").index();
Community
  • 1
  • 1
connexo
  • 53,704
  • 14
  • 91
  • 128