tags:

views:

204

answers:

3

Hi, I have a div, where in i do have a ul, where the ul has some li.

i just want to find some text and remove the li from the ul.

suppose eg:

<div id="div1">
  <ul>
    <li>Hello</li> <!--i need to remove this.-->
  </ul>
</div>
+5  A: 

With jQuery, you can do this:

$("#div1 ul li:contains('Hello')").remove();
Dominic Rodger
+1 That'd work just fine. Do you really need to specify div#div1? Couldn't you have done #div1 or is there a reason for this?
marcgg
@marcgg, no, that's probably overly verbose. Removed.
Dominic Rodger
yep, you could leave `div` out
Nicky De Maeyer
You don't have to prefix tagname with id selector.
rahul
OP asked for JavaScript, not jQuery.
Mathias Bynens
-1, not Javascript.
Alex Bagnolini
+9  A: 
var div = document.getElementById('div1'),
    ul = div.getElementsByTagName('ul')[0],
    li = ul.getElementsByTagName('li'),
    len = li.length;

// Go backwards so that removing items has no effect
while (len--) {
    if ( /Hello/.test(getText(li[len])) ) {
        ul.removeChild(li[len]);
    }
}

function getText(node) {
    var s = '';
    node = node.firstChild;
    if ( node ) do {
        if ( node.nodeType === 3 ) {
            s += node.data;
        }
        if ( node.nodeType === 1 ) {
            s += getText(node);
        }
    } while ( node = node.nextSibling );
    return s;
}
J-P
+1 for not requiring a 20KB library for a single task.
kaba
This is the 2nd time in recent memory I've seen this recursive descent to get the textual representation of a node (the other is http://stackoverflow.com/questions/765419/javascript-word-count-for-any-given-dom-element/765427#765427), and of course jQuery's `text()` does it too. But why do this instead of `textContent || innerText` if you know you are dealing with an `Element` node as in this case? Genuinely curious....
Crescent Fresh
@Crescent, See the answer by Kangax here: http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox ... The recursive-DOM-walking approach is the simplest way to make sure it works properly in all browsers.
J-P
@J-P: I had read and upvoted that answer before, just forgot all about it. Thanks!
Crescent Fresh
A: 
function removeLi()
{
    var DIV = document.getElementById('div1');
    var LI = DIV.getElementsByTagName('li');
    LI[0].parentNode.removeChild(LI[0]); //remove the first li
    //LI[1].parentNode.removeChild(LI[1]); //remove the second li
}
Leo
That doesn't remove only `li`s which contain the text 'Hello', per his requirements.
Dominic Rodger