Home > front end >  Unable to select last button in list of <p>'s using CSS
Unable to select last button in list of <p>'s using CSS

Time:03-20

In the below code I want to select last ".button" using CSS. The number of p's are different and so does the .button's. I want to select the last .button in the list of p's.

<div >
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text
    <a  href="#">button</>
</p>
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text</p>
<p>dummy text
    <a  href="#">button</>
</p>
<p>dummy text</p>
<p>dummy text</p>
/*can be more p's here*/
</div>

CodePudding user response:

js:

const last = Array.from(
  document.querySelectorAll('.button')
).pop();

Jquery:

$(".button:last")

CodePudding user response:

If you want access it for styling, you can use the following in CSS:

p a:last-child {
      
    }

CodePudding user response:

The best answer is Reut answer

You can use

p:last-Child
{

}

To select the last child of p in this example, so if you want you can replace it with other attributes/classes or id's etc

Notice that this will work using CSS

CodePudding user response:

You cannot do this purely with CSS.

To do it with Javascript you would probably be best off being as specific as possible so as not to pick up any a elements that may be further buried inside the p elements.

This snippet assumes that the anchor elements you are interested in are the direct children of the p. Of course alter the selector if this changes:

const els = document.querySelectorAll('.container > p > a.button');
els[els.length - 1].style.background = 'magenta';
<div >
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text
    <a  href="#">button</a>
  </p>
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text</p>
  <p>dummy text
    <a  href="#">button</a>
  </p>
  <p>dummy text</p>
  <p>dummy text</p>
  /*can be more p's here*/
</div>

Note: the anchor elements in your question were not correctly terminated. (</a> required)

CodePudding user response:

If there's gonna be a unique value in the href attribute, you can also use css attribute selectors to do the task in pure css otherwise JavaScript is always an option.

CodePudding user response:

const allBtns = documnet.querySelectorAll('.container>button')
const lastOne = allBtn[allBtn.length-1]

CodePudding user response:

Should be:

.button:last-of-type{

}
  • Related