如果子<span>不存在,我如何隐藏父元素</span>

时间:2013-06-13 01:08:55

标签: jquery html css

我正在尝试隐藏任何父元素,其子元素不包含需要类的span标记。例如:

<html>
<body>
<div class="optionfield" id="fieldAdTitle">
      <label class="optionLabel" for="Title">
      <span class="required">*</span>
      Title
      <label class="optionLabel" for="Title">
   <input type="text" class="" value="" name="Title" id="Title">
</div>
<div class="optionfield" id="fieldAdTitle">
   <label class="optionLabel" for="Title">
      Title
   </label>
   <input type="text" class="" value="" name="Title" id="Title">
</div>
<div class="optionfield" id="fieldAdTitle">
   <label class="optionLabel" for="Title">
      Title
   </label>
   <input type="text" class="" value="" name="Title" id="Title">
</div>
</body>
</html>

4 个答案:

答案 0 :(得分:5)

一个单行,但可能没有其他答案那么有效:

$('.optionfield:not(:has(span.required))').hide();

行动中:

$('.optionfield:not(:has(span.required))').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="optionfield" id="fieldAdTitle">
      <label class="optionLabel" for="Title">
      <span class="required">*</span>
      Title
    </label>
    <input type="text" class="" value="" name="Title" id="Title" />

</li>
<div class="optionfield" id="fieldAdTitle">
   <label class="optionLabel" for="Title">
      Title
   </label>
    <input type="text" class="" value="" name="Title" id="Title" />
</div>
<div class="optionfield" id="fieldAdTitle">
   <label class="optionLabel" for="Title">
      Title
   </label>
    <input type="text" class="" value="" name="Title" id="Title" />
</div>

此外,您还有一些格式错误的HTML:您在第一个<label>中有两个未公开的<div>标记。

答案 1 :(得分:4)

你可以做到

$('.optionfield').each(function(){
    if($(this).find('span.required').length == 0){
        $(this).hide();
    }
});

证明在fiddle;)

答案 2 :(得分:2)

你可以试试这个:

    $('.optionfield') //Get your sources
    .filter(function(){ //APply filter
          return $(this).find('span.required').length == 0}) // to get the elements with no span.required as child
    .hide(); //hide the filtered out ones.

Demo

参见 filter()

答案 3 :(得分:1)

我个人建议:

// hide them all:
$('.optionfield').hide()
// find the descendant elements:
.find('span.required')
// having found them, find the closest ancestor:
.closest('.optionfield')
// show them:
.show().

参考文献:

相关问题