kapantzak
kapantzak

Reputation: 11750

Why does css selector return different length from jQuery selector

I have noticed that these two expressions return different length (Check the console):

var cssSelector =  $('#target').siblings('table > tbody > tr > td').length; // returns 0
var jQuerySelector =  $('#target').siblings('table').children('tbody').children('tr').children('td').length; // returns 1
console.log('cssSelector: ' + cssSelector);
console.log('jQuerySelector: ' + jQuerySelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="target">Target</div>
<table>
  <tbody>
    <tr><td>Cell</td></tr>
  </tbody>
</table>

I would expect that they both select the same element, so they would return the same result.

Upvotes: 0

Views: 40

Answers (3)

dippas
dippas

Reputation: 60563

because table is sibling of #target and you are saying that td is sibling in your var cssSelector, which isn't correct, because td is a child of the table.

var cssSelector =  $('#target').siblings('table').length; // returns 1
var jQuerySelector =  $('#target').siblings('table').children('tbody').children('tr').children('td').length; // returns 1
console.log('cssSelector: ' + cssSelector);
console.log('jQuerySelector: ' + jQuerySelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="target">Target</div>
<table>
  <tbody>
    <tr><td>Cell</td></tr>
  </tbody>
</table>

Upvotes: 1

Developer107
Developer107

Reputation: 1758

Here $('#target').siblings('table') gives table which is a sibling of #target and then you need to parse through its children by .find("tbody > tr > td")

var cssSelector =  $('#target').siblings('table').find("tbody > tr > td").length; // returns 0
var jQuerySelector =  $('#target').siblings('table').children('tbody').children('tr').children('td').length; // returns 1
console.log(cssSelector);
console.log(jQuerySelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="target">Target</div>
<table>
  <tbody>
    <tr><td>Cell</td></tr>
  </tbody>
</table>

Upvotes: 0

BoltClock
BoltClock

Reputation: 723598

.siblings('table > tbody > tr > td') matches td elements. You can tell because the subject of the selector is td. Since #target's sibling is a table, not a td, this won't match anything.

.siblings('table') matches table elements. You then follow up with a series of .children() calls that drills down to the table's td descendants, producing a successful match.

Upvotes: 1

Related Questions