html - Matching the first/nth element of a certain type in the entire document -


how can specify :first-of-type of entire document?

i want style first <p> of html, no mater located (i don't want write section p:first-of-type because may located elsewhere in different html document).

p {    background:red;	  }    p:first-of-type {    background:pink;  }    p:last-of-type {    background:yellow;	  }
<body>    <section>      <p>111</p>      <p>222</p>      <p>333</p>    </section>    <p>444</p>    <p>555</p>  </body>

with css alone unfortunately isn't possible. documentation :first-of-type pseudo-class states:

the :first-of-type pseudo-class represents element first sibling of type in list of children of parent element.

this means :first-of-type applied first element of type relative parent , not document's root (or body element, in case).


javascript solutions

:first-of-type

we can achieve introducing javascript. need javascript's queryselector() method, pulls first matching element selector specified.

in example i've altered :first-of-type pseudo-class instead class of "first-of-type", used javascript add class element returned when using queryselector('p'):

document.queryselector('p').classname += ' first-of-type';
p {    background:red;	  }      p.first-of-type {    background: pink;  }
<body>    <section>      <p>111</p>      <p>222</p>      <p>333</p>    </section>    <p>444</p>    <p>555</p>  </body>

:nth-child , :last-of-type

as :nth-child , :last-of-type, can instead make use of similar method javascript gives us: queryselectorall(). method pulls all matching elements nodelist (which similar array), can iterate through or select specific elements within through index:

var elems = document.queryselectorall('p');    // nth-of-type = nodelist[n - 1]  // e.g. select 3rd p element ("333"):  if (elems.length >= 2)     elems[2].classname += ' nth-of-type';    // last-of-type = nodelist length - 1  if (elems.length)     elems[elems.length - 1].classname += ' last-of-type';
p {    background:red;	  }      p.nth-of-type {    background: pink;  }    p.last-of-type {    background: yellow;  }
<body>    <section>      <p>111</p>      <p>222</p>      <p>333</p>    </section>    <p>444</p>    <p>555</p>  </body>

note i've included if statements around both selectors ensure elems nodelist has enough elements, otherwise error thrown.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -