Neil Neil - 3 months ago 8
HTML Question

Select first element of a type on page even when elements are nested at different levels

I am practicing with CSS selectors. I know I could do this easily by specifying a

class
or an
id
, but for the purpose of the exercise: I'm curious if the following is possible without using those two CSS tools:

Imagine that I have have a whole bunch of
p
elements, and each
p
element is nested an unknown number of times in unknown block type elements. Ultimately I want to grab the very first
p
element that appears on the page and color its text red. How would I do that?

My following attempt does not work because the
:first-of-type
selector just grabs the first
p
element of its parent, so that doesn't help me here because each
p
element has different parents, so all the
p
elements on the page get selected.

I also attempted to wrap everything inside a
div
and then just grab the first
p
element inside that global
div
, but that didn't work either:

div:first-of-type p:first-of-type{
color: red;
}




p:first-of-type{
color: red;
}

<div>
<p> p element at one nesting</p>
</div>

<p> p element not nested</p>

<h1>
<p> p element at one nesting (oddly nested inside h1 tag)</p>
</h1>

<div>
<div>
<p> p element at two nestings</p>
</div>
</div>




Answer

When there is an unspecified depth and no class assignments it becomes very difficult to target this without traversing the DOM Using Just plain-ol-vanilla css I don't see a way to do this but using a tiny jQuery you can achieve it

var ps = $('p');

console.log(ps[0])
$(ps[0]).css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> 
  <p> p element at one nesting</p>
</div>

<p> p element not nested</p>

<h1>
  <p> p element at one nesting (oddly nested inside h1 tag)</p>
</h1>

<div>
  <div> 
    <p> p element at two nestings</p>
  </div>
</div>