如何隐藏p标签中的所有内容,除了span jQuery

How to hide everything inside a p tag except span jQuery?

本文关键字:jQuery span 除了 何隐藏 隐藏 标签      更新时间:2023-09-26

我有一个<p>标签,我需要隐藏文本。还有一个<span>里面的<p>,我不想隐藏这个文本。这是可能做到不改变标记使用jQuery吗?

小提琴:http://jsfiddle.net/ghogdc0x/2/

html:

<p class="class">
    <span>Text not to hide</span>
    <br>
    Text to hide
</p>

你可以使用css visibility属性:

$('.class').css('visibility', 'hidden');
$('.class').children().css('visibility', 'visible');

这是一个工作的代码依赖

然后你可以让它再次可见:

$('.class').css('visibility', 'visible');

您可以简单地复制span元素附近的p标记,然后隐藏p标记。试试这个:

$("p").after($("p span"))
$("p").hide()

使用此方法并尝试将要隐藏的文本包装在包装器p元素中,如

<p><span>Text not to hide</span><br/><p>Text to hide</p></p>
$('p').find('*').not('span').css('display','none');

不能隐藏文本节点。您只能删除它们,或者用另一个元素包装它们,并隐藏该包装器元素。

下面的代码片段隐藏了非span元素并删除了文本节点子元素。

$('p.class').contents().each(function() {
    var $this = $(this);
    if ( this.nodeType === 3 && $.trim(this.nodeValue) ) {
        $this.remove();
        // in case that you just want to hide the text node
        // $this.wrap('<i>').parent().hide();
   } else if ( this.nodeType === 1 && this.tagName !== 'SPAN' ) {
       $this.hide();
   }
});
http://jsfiddle.net/xxpopvje/