depperm
depperm

Reputation: 10746

Differing jquery table results

While attempting to get the proper jquery for this question I ran into a question. Shouldn't each of these have similar outputs? The first one doesn't even output the class of the divs

var list = document.querySelectorAll('[aria-label="Help"]');
console.log('&&&&&&&&&&&&&&');
$('[aria-label="Help"] tr div').each(function() {
  console.log($(this).attr('class'));
  console.log($(this).text());
});
console.log('&&THIS ONE WORKS&&&');
$('.text:not(:contains(X-Men 2),:contains(X-Men 3))').each(function() {
  console.log($(this).text());
});
console.log('&&&&&&&&&&&&&&');
$('[aria-label="Help"] .text:not(:contains(X-Men 2),:contains(X-Men 3))').each(function() {
  console.log($(this).text());
});
console.log('&&&&&&&&&&&&&&');
$('.text:not(:contains(X-Men 2),:contains(X-Men 3))',$(list)).each(function() {
  console.log($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id=5 aria-label="Help">
  <thead></thead>
  <tbody>
    <tr>
      <div class='abc'>
        <label><a><span class='text'>Game of thrones</span></a></label>
      </div>
    </tr>
    <tr>
      <div class='abc'>
        <label><a><span class='text'>Harry Potter</span></a></label>
      </div>
    </tr>
    <tr>
      <div class='abc'>
        <label><a><span class='text'>X-Men</span></a></label>
      </div>
    </tr>
    <tr>
      <div class='abc'>
        <label><a><span class='text'>X-Men 2</span></a></label>
      </div>
    </tr>
    <tr>
      <div class='abc'>
        <label><a><span class='text'>X-Men 3</span></a></label>
      </div>
    </tr>
  </tbody>
</table>

Upvotes: 1

Views: 30

Answers (1)

Jason P
Jason P

Reputation: 27012

Putting a div inside a tr is invalid html, so the browser "fixes" the layout for you, breaking your selectors that rely on the expected hierarchy.

Here's what the inspector shows:

<div class="abc">
  <label><a><span class="text">Game of thrones</span></a></label>
</div>
<div class="abc">
  <label><a><span class="text">Harry Potter</span></a></label>
</div>
<div class="abc">
  <label><a><span class="text">X-Men</span></a></label>
</div>
<div class="abc">
  <label><a><span class="text">X-Men 2</span></a></label>
</div>
<div class="abc">
  <label><a><span class="text">X-Men 3</span></a></label>
</div>
<table id="5" aria-label="Help">
  <thead></thead>
  <tbody>
    <tr>

    </tr>
    <tr>

    </tr>
    <tr>

    </tr>
    <tr>

    </tr>
    <tr>

    </tr>
  </tbody>
</table>

https://jsfiddle.net/bduhtfL6/

Upvotes: 3

Related Questions