skip to Main Content

Complete novice in JS/jQuery here just trying to do what I can while we fill in a senior dev role at work.

I’m trying to add to the end of these tags "Discount applied in cart". I was going to do this using an :after and "content" tag in css however this tag should only be added to the first 3 tags listed below and not the last 4.

<a class="externalLink">SAVE X%</a>
<a class="externalLink">SPEND $X SAVE X%</a>
<a class="externalLink">EXTRA X% OFF - ONLINE ONLY</a>

<a class="externalLink">BONUS GIFT</a>
<a class="externalLink">BUY 2 FOR $X</a>
<a class="externalLink">COMPLIMENTARY DELIVERY</a>
<a class="externalLink">REDEEM $X</a>

I tried googling a solution and stitched different bits of code together. I have tried the following to at least make the first one work, but unfortunately it didn’t work

$("a.externalLink:contains('SAVE')").html(function(_, html) {
return html.wrapAll('<span class="applied-cart" />');
});

Essentially what I’m hoping to do is change the code to the following

<a class="externalLink"><span class="applied-cart">SAVE X%</span></a>

with the css

.applied-cart:after {
content="Applied in cart";
}

2

Answers


  1. Using your existing $("a.externalLink:contains('SAVE')"), you can use .addClass to apply your class directly to the a without the need to .wrap or otherwise add additional HTML.

    $("a.externalLink:contains('SAVE')").addClass("applied")
    .applied:after {
      color:rebeccapurple;
      content:"Applied in cart";
      margin-left:1em;
    }
    
    a { display:block; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a class="externalLink">SAVE X%</a>
    <a class="externalLink">SPEND $X SAVE X%</a>
    <a class="externalLink">EXTRA X% OFF - ONLINE ONLY</a>
    <a class="externalLink">BONUS GIFT</a>
    <a class="externalLink">BUY 2 FOR $X</a>
    <a class="externalLink">COMPLIMENTARY DELIVERY</a>
    <a class="externalLink">REDEEM $X</a>
    Login or Signup to reply.
  2. No JS required, just use the power of advanced CSS selectors:

    div {
      white-space: pre-line; /* just for better readability of the output */
    }
    
    .externalLink:not(.externalLink:nth-of-type(3)~.externalLink)::after {
      content: " Content added by CSS";
      color: orange;
    }
    <div>
      <a class="externalLink">SAVE X%</a>
      <a class="externalLink">SPEND $X SAVE X%</a>
      <a class="externalLink">EXTRA X% OFF - ONLINE ONLY</a>
    
      <a class="externalLink">BONUS GIFT</a>
      <a class="externalLink">BUY 2 FOR $X</a>
      <a class="externalLink">COMPLIMENTARY DELIVERY</a>
      <a class="externalLink">REDEEM $X</a>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search