0

How do I do something like "Select all elements, whose child match a certain selector"?

For example. There are some elements <div>, each of these elements has a <a> child, some of these are <a class="typ1">, and some of these are <a class="typ2">. I want to select all <div> elements, that have an <a> child with a typ1 class.

I know that if I want to <a> elements I can do something like a.typ1', but how do I get the` parent?

RexMan85
  • 59
  • 1
  • 1
  • 6
  • 2
    That's often called a parent selector, and it doesn't exist in CSS. You have to do this with JS instead, or find another solution. There will be a _sort of_ parent selector in CSS soon, but it seems even that will only work via JS. (http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – ralph.m Apr 17 '15 at 05:56

2 Answers2

0

As of now, there is NO WAY to refer back to parent in CSS. Please refer to this W3 documentation.

Community
  • 1
  • 1
Prashant Ghimire
  • 4,658
  • 2
  • 30
  • 42
0

There is no way to select parent using css. but you can use jquery to do this.

see the fiddle here

HTML

<div>
    <a class="type-1">as</a>
</div>
<div>
    <a class="type-2">asd</a>    
</div>
<div>
       <a class="type-3">asd</a>    
</div>

CSS

.type-1-parent{
    background:red;

}
.type-2-parent{
    background:blue;

}
.type-3-parent{
    background:green;

}

JQUERY

$(".type-1").parent("Div").addClass("type-1-parent");
//or use closest method
//$(".type-1").closest("Div").addClass("type-1-parent");
$(".type-1").parent("Div").addClass("type-1-parent");
$(".type-2").parent("Div").addClass("type-2-parent");
$(".type-3").parent("Div").addClass("type-3-parent");

I hope this is what you want

droidev
  • 6,829
  • 9
  • 57
  • 85
  • Why go straight to a jQuery "solution" when the original question gives no indication that jQuery is being used. Proper JavaScript should be supplied instead. – Shaggy Apr 17 '15 at 16:53
  • @Shaggy Why use JavaScript if Jquery has more flexibility, extensibity and support – droidev Apr 18 '15 at 04:01
  • The original comment did not mention jQuery or Javascript. – garryp Dec 09 '15 at 14:44
  • 2
    The OP asked about css, since there is no possible solution with css for the requirement I suggested a solution using jquery – droidev Dec 09 '15 at 16:02
  • @droidev JQuery would add thousands of lines for this simple task – user3531149 Jul 17 '18 at 12:20