Home > Mobile >  Is there any way to remove html element by context?
Is there any way to remove html element by context?

Time:07-12

i have this following html code

<ui id="fruits">
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
    <li>lemon</li>
    <li>melon</li>
</ui>

now the question is: is there any function in jquery like $("#furits").removeElement("apple") to remove a element by context?

I tried the remove function in jquery, however it can only remove element by class,id,name etc, but i want remove a element by context?

thx.

CodePudding user response:

To achieve your goal you can use a combination of :contains and remove(), like this:

$('#fruits li:contains("apple")').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ui id="fruits">
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
    <li>lemon</li>
    <li>melon</li>
</ui>

It's worth noting that :contains is both a greedy match and also case-sensitive. This means Apple would not match apple, but would match Crab Apple, for example.

If you require an exact match you could use filter() instead:

let search = 'apple';
$('#fruits li').filter((i, el) => el.textContent.trim() === search).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ui id="fruits">
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
    <li>lemon</li>
    <li>melon</li>
</ui>

CodePudding user response:

I think this could help

$("#fruits li").remove( ":contains('apple')" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ui id="fruits">
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
    <li>lemon</li>
    <li>melon</li>
</ui>

CodePudding user response:

Not to my knowledge. You would need to iterate through the children and compare values.

$('#fruits li').each(function(){
   if ($(this).text() === 'apple') {
       $(this).remove();
   }
});

CodePudding user response:

You can create your own function from where you can remove child elements as:

const fruitsEl = document.querySelector("#fruits");

function removeChild(elementToRemoved) {
  if (elementToRemoved && fruitsEl) {
    const children = [...fruitsEl.children];
    for (let child of children) {
      const text = child.textContent.trim();
      if (text === elementToRemoved) fruitsEl.removeChild(child);
    }
  }
}

removeChild("apple");
<ui id="fruits">
  <li>apple</li>
  <li>orange</li>
  <li>banana</li>
  <li>lemon</li>
  <li>melon</li>
</ui>

  • Related