2

I need this kind of div

<div id="out">
    <table id="tab">
        <tr><th>A</th></tr>
        <tr><td>B</td></tr>
    </table>
</div>

and at a certain point I need to execute this instruction:

$("#out > #tab > tr > td").css( "background-color", "rgb(0, 255, 0)"); 

because I need all the td to have a green background. If instead of #out>td I use either #out or td it works fine, but not like this. Can you tell me why? jQuery library is already included.

$("#out > #tab > tr > td").css("background-color", "rgb(0, 255, 0)");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out">
  <table id="tab">
    <tr>
      <th>A</th>
    </tr>
    <tr>
      <td>B</td>
    </tr>
  </table>
</div>

6
  • 2
    $("#out > td") > in a css selector specifies a direct descendent. td is not a direct descendent here. Remove it and it will find the td. Commented Sep 12, 2018 at 16:38
  • Youe need a selector like this #out > #tab > tr > td Commented Sep 12, 2018 at 16:39
  • Just so it is clear, this is not a jQuery issue. This same selector (#out > td) in a css rule would not do what you are expecting. This is purely a selector issue. Commented Sep 12, 2018 at 16:43
  • I tried but it doesn't work Commented Sep 12, 2018 at 16:46
  • Edit the question and show us what you tried? Commented Sep 12, 2018 at 16:47

1 Answer 1

1

Your fully qualified selector is not working because you left out the tbody tag that the browser will create. I've provided two examples. One using the fully qualified version, and another using the indirect selector.

$("#out > #tab > tbody > tr > th").css("background-color", "rgb(255, 0, 0)");
$("#out td").css("background-color", "rgb(0, 255, 0)");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out">
  <table id="tab">
    <tr>
      <th>A</th>
    </tr>
    <tr>
      <td>B</td>
    </tr>
  </table>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.