Selecting untagged text with Jquery

拜拜、爱过 提交于 2019-12-13 01:04:51

问题


I have the following HTML;

<p class="postcontent">
<img src="#">
Some Text
</p>

I want to be able to hide only the text. So far I have this;

  jQuery(function($) {
$(".postcontent").$('[type=text]').hide();
  });

Edit: I don't have any control over the html so I need to add it by Jquery.


回答1:


You can wrap the text on the FLY and then hide it:

HTML:

<p class='postcontent'> <a href=#> dsds </a> aaa </p>

Javascript:

$('.postcontent').contents().filter(function() {
     return this.nodeType == 3; })
             .wrap('<label"> <label />').parent().hide();

JSFiddle


Update based on a comment:
Why does it create two labels? that's easy because it has two text nodes...:

<p class='postcontent'> (!!FirstTextNode!!)
    <a href=#> dsds </a> (!!SecondTextNode!!) aaa 
</p>    



回答2:


You can't apply CSS to a text node directly, as far as I know.

You probably need to wrap the text you want to hide in a new element like a div or span. Try something like

<p class="postcontent">
<img src="#">
<span class="posttext">
Some text
</span>
</p>

Then

$(".postcontent .posttext").hide();



回答3:


You will have to wrap the text in another element, such as a span or a label and hide that:

HTML

<p class="postcontent">
    <img src="#">
    <label>some Text</label>
</p>

JQuery

$(".postcontent > label").hide();    



回答4:


If for some reason you can't edit the source html, you would have to use .contents to get the text nodes:

$(".postcontent").contents().each(function(){
    if(this.nodeType == 3){
        $(this).wrap("<div>").parent().hide();
    } 
});

http://jsfiddle.net/Wg6Pw/




回答5:


This will clear the text in your example. You could then store the text and add it back in if you needed to. Here's a jsfiddle that breaks down how it works: http://jsfiddle.net/brentmn/SXgZc/

var pc = $('.postcontent');
pc.html(pc.html().replace(pc.text().trim(), ''));



回答6:


Put the text you want to hide in an element, and then hide by calling the id.



来源:https://stackoverflow.com/questions/9072905/selecting-untagged-text-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!