jQuery:除了2个特定元素之外,如何隐藏div中的所有内容

时间:2017-03-07 10:54:49

标签: javascript jquery jquery-selectors show-hide

我有以下HTML代码:

<div>
    <div class="firstclass secondclass">

        <intro><p>This is the first intro...</p></intro>
        <p><button>Button 1</button></p>
        <p>This is the first text paragraph</p>

        <intro><p>This is the second intro...</p></intro>
        <button>Button 2</button>
        <p>This is the second text paragraph</p>
        This is another text paragraph, but without the <p> element

    </div>
</div

我想以下输出usind jQuery:

This is the first intro...
Button 1
This is the second intro...Button 2

我正在尝试这段代码:

$('div.item_desc.custom_content :not(intro, button)').hide()

我得到的是:

This is another text paragraph, but without the <p> element

我正在使用自定义intro-tag进行进一步处理。请注意,button-element一次位于p元素内,另一次不在p元素内。此外,文本的一部分不在p元素中,但我也希望隐藏此文本。我定义需要使用hide命令(因为进一步的限制)。我如何修改我的jQuery代码?

2 个答案:

答案 0 :(得分:0)

未测试:

$('div.item_desc.custom_content').children("intro:not(:first), p:not(:eq(0)), p:not(:eq(1))")

但是,更简单的解决方案是创建一个类alwaysshown

<div>
    <div class="firstclass secondclass">

        <intro class="alwaysshown"><p>This is the first intro...</p></intro>
        <p class="alwaysshown"><button>Button 1</button></p>
        <p class="alwaysshown">This is the first text paragraph</p>

        <intro><p>This is the second intro...</p></intro>
        <button>Button 2</button>
        <p>This is the second text paragraph</p>
        This is another text paragraph, but without the <p> element

    </div>
</div>

然后:

$('div.item_desc.custom_content').children(":not("alwaysshown")")

答案 1 :(得分:0)

<!DOCTYPE html>

&#13;
&#13;
$(document).ready(function(){
  var htmlString = $(".firstclass").html(); 
  var data=''; var getthis='';
 $(".firstclass").find(":button, intro").each(function () {
var getthis = $( this ).html();
data += getthis;	            
});
$(".firstclass").html( data );
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

<div class="firstclass secondclass">

        <intro><p>This is the first intro...</p></intro>
        <p><button>Button 1</button></p>
        <p>This is the first text paragraph</p>

        <intro><p>This is the second intro...</p></intro>
        <button>Button 2</button>
        <p>This is the second text paragraph</p>
        This is another text paragraph, but without the <p> element

    </div>

</body>
</html>
&#13;
&#13;
&#13;

        

这是第一个介绍...

        

按钮1

        

这是第一段文字

        

这是第二个介绍...

        按钮2         

这是第二段文字

        这是另一个文本段落,但没有

元素     

经过测试的代码工作正常希望它有所帮助。