Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery remove text between tags

Tags:

jquery

I have such html:

<li>
  <a href="#">2012: Ice Age</a>
  <br>
  <a href="#"> blah blah </a>
  <br>
     This text should disappear!!!
</li>

How to I remove that text with Jquery? I don't have a control over this code, so I cannot add any IDs for easier selection..

like image 318
Stewie Griffin Avatar asked Dec 27 '22 18:12

Stewie Griffin


2 Answers

$('li').contents().last().remove();

If it is at the end, you can use the contents()[docs] method (which gets all children, including text nodes, and the last()[docs] method to target the last one.

Example: http://jsfiddle.net/KtTfQ/


EDIT:

You could also just empty the content of that text node:

$('li br:last-child')[0].nextSibling.nodeValue = '';

Example: http://jsfiddle.net/KtTfQ/2/

like image 129
user113716 Avatar answered Jan 05 '23 00:01

user113716


It's easiest done with plain old DOM manipulation:

var text = $("li").get(0).lastChild;
text.parentNode.removeChild(text);

Fiddle: http://jsfiddle.net/LBxqa/1/

like image 37
Magnar Avatar answered Jan 05 '23 00:01

Magnar