terrid25
terrid25

Reputation: 1946

targetting text in between elements

I have the following HTML

<ul>
  <li>
  some text here
  <ul>
    <li>cat1</li>
  </ul>
 </li> 
</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

Upvotes: 0

Views: 142

Answers (2)

bcoughlan
bcoughlan

Reputation: 26627

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;
}

Upvotes: 0

user113716
user113716

Reputation: 322502

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.

Upvotes: 1

Related Questions