Home > Enterprise >  How to display different text and links in html depending on the class that its embedded in
How to display different text and links in html depending on the class that its embedded in

Time:10-10

I want to display different text and links depending on the category/class that the code is embedded in. The following works in that it displays "Read more about Apples" or "Read more about Oranges" depending on the category/class that the code is embedded in. However I also want it to include different hyperlinks. I thought that the last two lines would do the job but the text doesn't appear with hyperlinks in it. Any ideas?

<style>
.category-apples themainbodya::after {
  content: " Apples";
}
.category-oranges themainbodyb::after {
  content: " Oranges";
}
</style>
<p>Read more about</p>
<themainbodya href=https://testa.test.com/ ></themainbodya>
<themainbodyb href=https://testo.test.com/ ></themainbodyb>

CodePudding user response:

Thanks to the hint from A Haworth I worked out the answer. HOWEVER I still can't work out how to add a different image depending on whether it's apples or oranges.

<style>
.category-apples .themainbodya::after {
  content: " Apples";
}
.category-oranges .themainbodyb::after {
  content: " Oranges";
}
</style>
<p>Read more about</p>
<a class=themainbodya href=https://testa.test.com/ ></a>
<a class=themainbodyb href=https://testo.test.com/ ></a>

CodePudding user response:

I am a little worried that using pseudo elements that way could make the site a little less accessibility friendly as screen readers may not read out their content.

This snippet uses a slightly different method, the text 'apples', 'oranges' (and any other fruit) is put into the relevant element (as is an image just to show one way of it being done, though you may prefer to use background-image). Those elements are set to display: none initially, and then they display depending on which of the categories is set in the class list of the containing element.

As there are only two elements in the test, the toggle function is used to go between them, but of course for more elements you will want a bit more JS to remove the unwanted classes.

*[class*="themainbody"] {
  display: none;
}

.category-apples .themainbodya {
  display: block;
}

.category-oranges .themainbodyb {
  display: block;
}

.container img {
  width: 100px;
  height: 100px;
}
<button onclick="const c = document.querySelector('.container'); c.classList.toggle('category-oranges'); c.classList.toggle('category-apples');">Toggle between oranges and apples</button>
<div >
  <p>Read more about</p>
  <a class=themainbodya href=https://testa.test.com/><img src="https://i.stack.imgur.com/W4FFq.jpg" alt="apple">Apples</a>
  <a class=themainbodyb href=https://testo.test.com><img src="https://i.stack.imgur.com/wsIvt.png" alt="orange">Oranges</a>
</div>

  • Related