javascriptjqueryhtmlcsscss-selectors

A Multi-Level Up Css Selector


I'm trying to find a way to use css selectors to format a specific parent div. For example, in the following sample code...

<div id="one">
   <div id="two"
      <div id="three">
         <a href="foo.html">something</a>

...etc

I want to format div#one but only if the link inside of #one is a specific page like "foo.html".

I have tried several things but here is one example of what I have tried to use...

a[href *="foo"] #one:parent {
    background-color: #FF0000;
}

Is there a way to do this using css selectors, js or jQuery? I've included a code snippet below for testing...

a[href *="foo"] #one:parent {
        background-color: #FF0000;
    }
    <div id="one">
       <div id="two"
          <div id="three">
             <a href="foo.html">something</a>
          </div>
       </div>
    </div>
    

Everywhere I have searched for an answer has only given clues to how to do this with parent elements that are just one parent above but not several divs as in this example.


Solution

  • With CSS you cannot but with JS you can simply consider parentNode:

    document.querySelector('a[href *="foo"]').parentNode.parentNode.parentNode.style.backgroundColor = "red";
    #one {
     padding:50px;
    }
    <div id="one">
      <div id="two">
        <div id="three">
          <a href="foo.html">something</a>
        </div>
      </div>
    </div>

    And if you have n parent and you don't know the number you can create a loop to find your element:

    var a = document.querySelector('a[href *="foo"]');
    while (a.parentNode.getAttribute('id') != "one") {
      a = a.parentNode;
    }
    a.parentNode.style.background = "red";
    #one {
      padding: 50px;
    }
    <div id="one">
      <div id="two">
        <div id="three">
          <div>
            <a href="foo.html">something</a>
          </div>
        </div>
      </div>
    </div>