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 >SAVE X%</a>
<a >SPEND $X SAVE X%</a>
<a >EXTRA X% OFF - ONLINE ONLY</a>
<a >BONUS GIFT</a>
<a >BUY 2 FOR $X</a>
<a >COMPLIMENTARY DELIVERY</a>
<a >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 />');
});
Essentially what I'm hoping to do is change the code to the following
<a ><span >SAVE X%</span></a>
with the css
.applied-cart:after {
content="Applied in cart";
}
CodePudding user response:
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 >SAVE X%</a>
<a >SPEND $X SAVE X%</a>
<a >EXTRA X% OFF - ONLINE ONLY</a>
<a >BONUS GIFT</a>
<a >BUY 2 FOR $X</a>
<a >COMPLIMENTARY DELIVERY</a>
<a >REDEEM $X</a>
CodePudding user response:
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 >SAVE X%</a>
<a >SPEND $X SAVE X%</a>
<a >EXTRA X% OFF - ONLINE ONLY</a>
<a >BONUS GIFT</a>
<a >BUY 2 FOR $X</a>
<a >COMPLIMENTARY DELIVERY</a>
<a >REDEEM $X</a>
</div>