admin管理员组

文章数量:1397093

The code below can get the html table tds with attribute 'rowspan',

 $elem.find('td').filter('[rowspan]') 

but how can I get the tds who's 'rowspan' is more than 1,like:

$elem.find('td').filter('[rowspan > 1]')

The code below can get the html table tds with attribute 'rowspan',

 $elem.find('td').filter('[rowspan]') 

but how can I get the tds who's 'rowspan' is more than 1,like:

$elem.find('td').filter('[rowspan > 1]')
Share Improve this question edited Dec 22, 2016 at 14:56 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 8, 2016 at 10:07 nateenatee 552 silver badges8 bronze badges 1
  • anyone know how to do this with Vanilla? – Michael Martell Commented Dec 23, 2022 at 21:55
Add a ment  | 

5 Answers 5

Reset to default 5

You can apply a function to your filter and return elements whose rowSpan is greater than 1:

$.elem.find('td').filter(function() {
  return this.rowSpan > 1;
});

Note that there's no need to wrap attr() or re-wrap this (as $(this)) as rowSpan is a native element property (which is conveniently already a numeric type, so no number conversion is needed).

Example

$('td').filter(function() {
    return this.rowSpan > 1;
}).css('color', 'red')
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>No rowspan</td>
      <td rowspan=1>Rowspan 1</td>
      <td rowspan=2>Rowspan 2</td>
    </tr>
  </tbody>
</table>

Try something like this :-

$elem.find('td').filter(function(){
   return (parseInt($(this).attr('rowspan'),10) > 1);
});

use : parseInt($(this).attr('rowspan'),10) > 1

You can iterate in each td element and check if attribute rowspan is > 1. In my example I use css class to represent if a td has rowspan > 1 adding to this element class pass or fail accordingly.

$("table tbody tr td[rowspan]").each(function() {
  $(this).addClass(parseInt($(this).attr("rowspan"), 10) > 1 ? "pass" : "fail");
});
.pass {
  background: green;
}
.fail {
  background: red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td rowspan='2'>2</td>
      <td rowspan='3'>3</td>
      <td>no rowspan</td>
      <td rowspan='1'>1</td>
    </tr>
    <tr>
      <td rowspan='2'>2</td>
      <td rowspan='3'>3</td>
      <td>no rowspan</td>
      <td rowspan='1'>1</td>
    </tr>
    <tr>
      <td rowspan='2'>2</td>
      <td rowspan='3'>3</td>
      <td>no rowspan</td>
      <td rowspan='1'>1</td>
    </tr>
  </tbody>
</table>

To get the tds who's 'rowspan' is more than 1, you may try the following:

var allTdsWithMoreThanOneRowspan = $elem.find('td[rowspan]').filter(function () {   
   return ($(this).attr('rowspan') > 1);
})

本文标签: javascriptjQuery how to select td with rowspan attributeStack Overflow