anaBad anaBad - 5 months ago 10
Javascript Question

How to hide a HTML row by index?

I'm attempting to hide certain rows of my HTML table based on their index but I get the error:


TypeError: $rows[0].hide is not a function


What am I doing wrong?

HTML:

<tbody id="searchable">
<c:forEach var="lot" items="${pageResult.entries}" varStatus="status">
<tr title="<c:out value='${lot.description}'/>">
<td><c:out value='${lot.nom}'/></td>
<td><fmt:formatNumber value="${lot.id}" pattern="0000"/></td>
<td><c:out value='${lot.priorite}'/></td>
<td>
<form:form class="actionForm" action="detail" method="POST">
<input type="hidden" name="lotId" value="<c:out value='${lot.nom}'/>"/>
<input type="submit" class="action editer" value="Editer"/>
</form:form>
<form:form class="actionForm" action="supprimer" method="POST" onsubmit="return confirm('Confirmer la suppression?')">
<input type="hidden" name="lotId" value="<c:out value='${lot.nom}'/>"/>
<input type="submit" class="action supprimer" value="Supprimer"/>
</form:form>
</td></tr>
</c:forEach>
</tbody>


Javascript:

var $rows = $('#searchable tr');
$(document).ready(function(){
$rows[0].hide();
});

Answer

You can use eq(), to select the item you want:

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.

var $rows = $('#searchable tr');
$(document).ready(function() {
  $rows.eq(0).hide();
  console.log($rows[0])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody id="searchable">
    <tr>
      <td>First Tr</td>
      <td>value1</td>
      <td>value2</td>
      <td>value3</td>
    </tr>
    <tr>
      <td>Second Tr</td>
      <td>value1.2</td>
      <td>value2.2</td>
      <td>value3.2</td>
    </tr>
  </tbody>
</table>