开发者

targetting text in between elements

I have the following HTML

<ul>
  <li>
  some text here
  <ul>
    <li>cat1</li>
  </ul>
 </li> 
&开发者_开发技巧lt;/ul>

<ul>
  <li>
  random stuff here
  <ul>
    <li>item1</li>
  </ul>
 </li> 
</ul>

Is there a way I can target the text in between the <ul><li> </ul> i.e. some text here and random stuff here? I'd really like to hide this text if possible.

Thanks


If you're ok with removing the text, instead of merely hiding it, you could do this:

$('ul > li:has(ul)').each(function() {    
   if( this.firstChild.nodeType === 3 ) {
       this.removeChild( this.firstChild );
   }
});

This looks at the top level <li> elements, check to see if their firstChild is a text node, and if so, removes it.

Example: http://jsfiddle.net/3B32a/

It would be better to identify the top level with a class on the ul elements.

If you actually want to show and hide it, it will need to be contained in an element, instead of a standalone text node.


To expand on patrick dw's solution, instead of removing the text you can wrap it in a tag:

$('ul > li:has(ul)').each(function() {
    if( this.firstChild.nodeType === 3 ) {
        $(this.firstChild).wrap('<span class="hidden" />');
    }
});

And your CSS:

.hidden {
    display: none;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜