0

I know I can select the descendant or sibling of a specific class with combinators. I have a situation where I want to style an element on any page where a totally separate element contains a certain class. This is for a wordpress site where some pages have a particular category, which adds that category's name to an element on the page. I want to style a totally separate element on any of those pages, but the element is not a descendant or sibling of the one with the class I'm looking for.

Imagine this simplified scenario:

<div>
    <div>
        <div class="desired-cat"></div>
    </div>
<div>
<div>
    <div>
        <div class="target-element"></div>
    </div>
<div>

Is it possible for me to style .target-element on any page where .desired-cat is used somewhere on that page? Thanks!

JohnMazz
  • 33
  • 4
  • Using pure CSS? No. Using jQuery? Maybe. No selector currently exists that can select a previous or parent element in pure CSS. Here's a list of all selectors currently available : https://www.w3.org/TR/selectors-3/#selectors – Alexandre Elshobokshy Jun 24 '20 at 13:34
  • You should add the category as a class to the detail page server side. That way it's easy to do custom category styling. – Wimanicesir Jun 24 '20 at 13:36
  • I don't think this is in the realm of CSS possibilities, it can't traverse the DOM tree "upwards" (to parents). You can achieve this quite simply with JavaScript though, using ```document.querySelector``` or ```document.getElementsByClassName``` to find your nodes and then use ```.classList.add("some-class")``` to style the target-element. – mikiqex Jun 24 '20 at 13:38
  • I've marked this as a duplicate of another question where I've written a bit of an encyclopedic answer - but the long and short of it is that there isn't a selector that checks for the presence of some other element anywhere within the page regardless of its location. – BoltClock Jun 30 '20 at 10:16

2 Answers2

0

you can use HTML Dom getlElementByClassName() method to select all elements in the HTML file.

function myFunction() {
  var x = document.getElementsByClassName("example");
  x[0].innerHTML = "Hello World!";
}
<html>
<body>

<div class="example">First div element with class="example".</div>

<div class="example">Second div element with class="example".</div>



<button onclick="myFunction()">Try it</button>



</body>
</html>
m3hm3tcan
  • 1
  • 1
  • 1
0

In WordPress you can use body classes.

Where each page, category, tag, etc., has its own class.

So you can use these classes to style specific areas.

Example:

...
<body class="archive category category-physiotherapy category-76 logged-in admin-bar wp-custom-logo hfeed customize-support">
...
Demartini
  • 101
  • 5