Brian Var
Brian Var

Reputation: 6227

How to remove a child li element by text value search key?

I have passed down a text value that matches the text of a li tab element in a list.

I then need to remove any tabs on the page matching that search text value. So for example I pass down "Chart1" to the ClearGraph method it should remove any tabs matching with that text value in the list.

So this is what I tried in the method, passed down the chart-text value and called .contains() then .remove():

    function clearGraph(chart_text)
    {
        //Remove the chart tab by the text value
        $('#chartTabs li:contains('+ chart_text + ")'").remove();

    }

But I get a console error when calling the method, jquery-2.2.2.js:1468 Uncaught Error: Syntax error, unrecognized expression: #chartTabs li:contains( Chart 1)'.

Question: How can you remove a child li element by text value search key?

The markup and associated ClearGraph method is defined as follows:

    <ul class="nav nav-pills" id="chartTabs">
        @* dynamically create the tab elements in d3 js *@
    </ul>


    function clearGraph(chart_text)
    {
        //Remove the chart tab by the text value
        $('#chartTabs li:contains('+ chart_text + ")'").remove();

    }

Upvotes: 0

Views: 71

Answers (2)

smoksnes
smoksnes

Reputation: 10851

You're missing a '

$('button').click(function()
{
  var input = $('input').val();
  $("#chartTabs li:contains('" + input + "')").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav nav-pills" id="chartTabs">
  <li>Foo</li>
  <li>Bar</li>
</ul>
<input type="text"/>
<button type="button">Clear</button>

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You have syntax error in your code. Extra quote in end is breaking the selector. You need to use:

$('#chartTabs li:contains('+ chart_text + ')').remove();

Upvotes: 0

Related Questions