skip to Main Content

How can I specify the first p element of each li tag belongs to the same class without doing it manually (in the case there are too many li tags in the ul element), as we know that :first-child pseudo-class only applies style attribute for element, not class attribute?

<ul>
  <li>
    <p>...</p>
    <p>...</p>
  </li>
  <li>
    <p>...</p>
    <p>...</p>
  </li>
</ul>

2

Answers


  1. You can use li > p:first-child as selector in the CSS:

    li > p:first-child {
      background-color: red;
    }
    <ul>
      <li>
        <p>...</p>
        <p>...</p>
      </li>
      <li>
        <p>...</p>
        <p>...</p>
      </li>
    </ul>

    If you really want to add a class to those elements then you can use JavaScript for it and the classList.add() function:

    const FirstParagraph = document.querySelectorAll('li > p:first-child');
    FirstParagraph.forEach(paragraph => {
      paragraph.classList.add('bg-red');
    })
    .bg-red {
      background-color: red;
    }
    <ul>
      <li>
        <p>...</p>
        <p>...</p>
      </li>
      <li>
        <p>...</p>
        <p>...</p>
      </li>
    </ul>
    Login or Signup to reply.
  2. Not sure if I get it your question or not. But my understanding is you want to select paragraphs that shares some specific class that under li element. If that is the case you can inspect the code below.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>Document</title>
        </head>
        <body>
            <ul>
                <li>
                    <p class="xyz">...</p>
                    <p>...</p>
                </li>
                <li>
                    <p class="xyz">...</p>
                    <p class="xyz">...</p>
                </li>
                <li>
                    <p class="zyx">...</p>
                    <p class="ldk2">...</p>
                </li>
            </ul>
    
            <script>
                const getParagraphElements = (givenClass) => {
                    const liList = [...document.querySelectorAll("li")];
                    const neededParagraphs = [];
                    liList.forEach((li) => {
                        const firstChildren = li.children[0];
                        if (firstChildren.classList.contains(givenClass)) {
                            neededParagraphs.push(firstChildren);
                        }
                    });
                    console.log(neededParagraphs);
                };
    
                getParagraphElements("xyz");
            </script>
        </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search