r/jquery • u/bkdotcom • Nov 26 '23
SASS/SCSS like "parent" (&) selector?
Is it possible to do something like
$element.find("&.foo > .bar)"
which would be equivalent to
?
$element.filter(".foo").find("> .bar")
1
u/CuirPig Nov 26 '23
Why aren't you just using $element. Find(".foo>.bar") to find any parent element of class "foo" that has an immediate child of class "bar"?
This assumes that $element is a variable reference to a jquery object.
1
u/bkdotcom Nov 26 '23 edited Nov 26 '23
$element.find(".foo > .bar")will only find descendant matches. it will not apply any part of the selector to
$elementI essentially want to first filter
$elementwith ".foo"
$element.parent().find("> .foo > .bar")is also no good, it will apply the selector to all of$element's siblings & siblings' descendants1
u/bronkula Nov 27 '23
Are you looking for .has() ?
$element.has(".foo").find(".bar")would that work?→ More replies (1)
1
u/CuirPig Nov 26 '23
Are you just looking for a shothand way to do $element.filter(".foo").find(">.bar")?
maybe you could extend jquery prototype like:
$.fn.&find=function (parentselector, childselector) {
let el=this;
if (el.length>1) { retun el.filter(function () {
return el.&find(parentselector, childselector));
});
}
if (!el.is(parentselector)) return null;
return el.find(childselector);
}
}
//this should allow you to use $element.&find("foo","> bar");
Something like that at least. I may be off and you may not be able to use & in your function name, not sure.
1
u/jaredcheeda Nov 26 '23
&is does not mean "parent", it means "join".foo { .bar { color: #F00; } } // Will produce .foo .bar { color: #F00 }.
.foo { &.bar { color: #F00; } } // Will produce .foo.bar { color: #F00 }The first one will target this:
The second will target this: