简体   繁体   English

从子div获取父div

[英]Get parent div from child div

I have below structure我有以下结构

<div class="A">
    <div title="Sales"></div>
</div>

Class A is common and present at many places on page hence i am not able to select appropriate div with class A. Class A 很常见,并且出现在页面上的许多地方,因此我无法 select 与 class A 适当的 div。

I have child div with title "sales" or anything else unique at each places, I am able to get that child div with below code div[title='Sales']{ background-color:skyblue; }我在每个地方都有标题为“sales”或其他任何独特内容的子 div,我可以使用以下代码获取该子 div div[title='Sales']{ background-color:skyblue; } div[title='Sales']{ background-color:skyblue; }

Now i want to select its parent div from above child div to apply background color to entire parent div Please help现在我想 select 它的父 div 从上面的子 div 应用背景颜色到整个父 div 请帮助

Why you don't solve this like my snippet.为什么你不像我的片段那样解决这个问题。 We probably solve em with css not js.我们可能用 css 而不是 js 来解决 em。 you are using parent in your js which makes your codes more and even there's no logic for doing this why we do hard thinks?!您在您的 js 中使用了 parent,这使您的代码更多,甚至没有逻辑这样做为什么我们要努力思考?!

 <div class="A Sales"> <div title="Sales"></div> </div> <div class="A Products"> <div title="Sales"></div> </div>

In CSS you can't access the parent div given a specific child element but you could fake this behaviour by adding a box-shadow to the child element, eg在 CSS 中,您无法访问给定特定子元素的父 div,但您可以通过向子元素添加box-shadow来伪造此行为,例如

 .A { border: 1px lightblue dashed; padding: 100px; overflow: hidden; } [title="Sales"] { border: 1px yellowgreen dashed; box-shadow: 0 0 0 100vmax skyblue; /* or a higher value */ }
 <div class="A"> <div title="Sales">Sales</div> </div>

The hidden overflow applied to the parent will clip the area of the shadow.应用于父级的隐藏溢出将剪切阴影区域。

As there are many tags in your question:由于您的问题中有很多标签:

Jquery: Jquery:

$("div[title='Sales']").parent()

or, better, with a filter on which parent:或者,更好的是,使用哪个父级的过滤器:

$("div[title='Sales']").parents(".A")

in vanilla JS:在香草 JS 中:

document.querySelectorAll("div[title='Sales']").parentNode

or或者

document.querySelectorAll("div[title='Sales']").parentElement

With CSS is currently not possible to select an element based on the child properties, but there are other ways to implement this behaviour.使用 CSS 目前无法将 select 元素基于子属性,但还有其他方法可以实现此行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM