xRobot
xRobot

Reputation: 26567

How to select an element inside another element?

I have this html code:

<td><a href="...">aaa</a></td>

<td><div><a href="...">bbb</a></div></td>

<td><a href="...">ccc</a></td>

I need a way to select ONLY the a inside a td and NOT inside a div too.

So in the example above I need to get:

<a href="...">aaa</a>
<a href="...">ccc</a>

How can I do that ?

Upvotes: 1

Views: 73

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371063

Target only anchor elements that are children of a td. A child combinator (>) matches only the children (direct descendants) of an element.

td > a {
  background-color: aqua;
}
<table>
  <td><a href="">aaa</a></td>
  <td>
    <div><a href="">bbb</a></div>
  </td>
  <td><a href="">ccc</a></td>
</table>

A descendant combinator (), which targets all descendants (not only the children), would not work because it would also match the anchor in the second td.

td a {
  background-color: aqua;
}
<table>
  <td><a href="">aaa</a></td>
  <td>
    <div><a href="">bbb</a></div>
  </td>
  <td><a href="">ccc</a></td>
</table>

Upvotes: 3

Ronit Mukherjee
Ronit Mukherjee

Reputation: 405

Using parent > direct-child selector

td > a {
  color: red;
  text-decoration: none;
}
<table>
  <tr>
    <td>
      <a href="#">aaa</a>
    </td>
    <td>
      <div>
        <a href="#">bbb</a>
      </div>
    </td>

    <td>
      <a href="#">ccc</a>
    </td>
  </tr>
</table>

Upvotes: 1

DSCH
DSCH

Reputation: 2366

You can select only immediate children by using > as so:

td>a { ...some styling }

Upvotes: 1

Related Questions