How to Select the Last Element of a Specific Class

Solution with CSS

To select the last element of a specific class, you can use the CSS :last-of-type pseudo-class.

In this snippet, we'll show examples with the HTML <article> and <p> elements.

Example of selecting the last <article> element of a specific class:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        background: #95ada2;
      }
      .comment {
        width: 470px;
        border: 1px solid #ffffff;
        padding: 10px;
        border-bottom: 2px dotted #f0f0f0;
        margin-bottom: 10px;
      }
      .comment:last-of-type {
        border-bottom: 3px dashed lightblue;
        margin-bottom: 0;
      }
    </style>
  </head>
  <body>
    <div class="commentList">
      <article class="comment"></article>
      <article class="comment"></article>
      <article class="comment"></article>
      <div class="text"> hello </div>
    </div>
  </body>
</html>

Result

hello

Example of selecting the last <p> element of a specific class:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .text:last-of-type {
        background: purple;
        font-style: italic;
        color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <h1>Example of :last-of-type selector </h1>
    <p class="text">Paragraph number 1.</p>
    <p class="text">Paragraph number 2.</p>
    <p class="text">Paragraph number 3.</p>
    <p class="text">Paragraph number 4.</p>
  </body>
</html>
Do you find this helpful?

Related articles