简体   繁体   中英

Hide span in second table row through jQuery

I have a table that is generated in flask:

<table class="table" id="preferencesTable">
  <thead>
    <th>
      <span>Fall 2016 Course Preferences</span>
      <span id="addPreference" class="glyphicon glyphicon-plus-sign pull-right"></span>
    </th>
  </thead>
  <tbody>
    {% for row in data.course_preferences %}
        <tr id="{{row.id}}">
          <td>
            {{ row.name }}
            <span class="pull-right">
              <span class="glyphicon glyphicon-arrow-up icon_padding"></span>
              <span class="glyphicon glyphicon-arrow-down icon_padding"></span>
              <span class="glyphicon glyphicon-remove icon_padding></span>
              <span class="glyphicon glyphicon-remove icon_padding></span>
            </span>
          </td>
        </tr>
    {% endfor %}
  </tbody>
</table>

I want to have the up and down arrows move the order of the table rows. Because the first table row (not including the header) is at the top, the up arrow is not needed. I want to hide this arrow.

I am able to find that span with the following:

$('#preferencesTable tr:nth-child(2) span')[2]

which returns

<span class=​"glyphicon glyphicon-arrow-down icon_padding">​::before​</span>​

But I lose all of the abilities to show and hide the span (.css, .hide, etc. are no longer valid).

How can I hide this span only on the first row?

You need to access the first child under the tbody of the table, then you can find the span with class glyphicon-arrow-up and hide it. Also using [2] to access the span will return a dom element reference not a jQuery object so you won't be able to call any jQuery methods using it.

The tr:nth-child(2) will select the tr which is the second child of its parent, in this case it will select the second tr in the tbody

$('#preferencesTable tbody tr:first-child span.glyphicon-arrow-up').hide()

The answer given by Arun P Johny seems to be correct.

I have additionaly created a jsfiddle: Click here to see the demo

You can put this JS inside an event handler so that on some action it always hide the up arrow for the first row.

$('selector').eventName(function(){
      $('#preferencesTable tbody tr:first-child span.glyphicon-arrow-up').hide();
});

I believe the problem is that when you use the square bracket operators, you get a vanilla JavaScript DOM object. Refer to: https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/

You can solve it by wrapping that DOM object in $() to get a jQuery object, as follows:

var firstRowSpan = $('#preferencesTable tr:nth-child(2) span')[2];
firstRowSpan = $(firstRowSpan);
firstRowSpan.hide();

See also: convert DOM to jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM