Home > Net >  How can i select every element before a specific element
How can i select every element before a specific element

Time:07-29

What i'm trying to do is add a border-radius to the last p of every "block" of p's so before the next h1, I can add the top radius using the selector but can't figure out how to select the last one of each.

<main>
    <h1>test</h1>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
</main>

css

<style>
  p {
    background: black
  }
  h1   p {
    border-top-left-radius: 1rem;
    border-top-right-radius: 1rem;
  }
</style>

CodePudding user response:

If you are open to deploying a dash of javascript, you can achieve this effect by adding a single line of javascript to the bottom of your page, like this:

<script>
[...document.getElementsByTagName('h2')].forEach((heading) => {if (heading.previousElementSibling) {heading.previousElementSibling.classList.add('last-paragraph')}});
</script>

</body>
</html>

Working Example:

[...document.getElementsByTagName('h2')].forEach((heading) => {if (heading.previousElementSibling) {heading.previousElementSibling.classList.add('last-paragraph')}});
p {
  height: 24px;
  margin: 0 0 -2px 0;
  padding: 6px 12px;
  line-height: 24px;
  border: 2px solid rgb(255, 0, 0);
  border-top: 2px solid rgba(0, 0, 0, 0);
  border-bottom: 2px solid rgba(0, 0, 0, 0);
}

h2   p {
  border-top: 2px solid rgb(255, 0, 0);
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

p.last-paragraph,
p:last-of-type {
  border-bottom: 2px solid rgb(255, 0, 0);
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}
<main>
    <h2>test</h2>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
</main>

CodePudding user response:

Wrap every block of <p> and use :last-child. If you're doing many <p> it is best to just add a class to each element that has the desired styles.

<div>

  <p>Hello</p>
  <p>Hey</p>

</div>
p:last-child{
  font-size: 30px; // only last element has a font size of 30 px
}

You also didn't close any of your <p> tags. Make sure your code is formatted before posting.

  • Related