Home > Enterprise >  how to remove specific buttons in jquery
how to remove specific buttons in jquery

Time:10-22

how can I remove specific buttons for example i have

<div>
<button>1</button>
<button>2</button>
<button>3</button>
</div>

then i want to delete specific buttons in jquery,i tried use remove function like this

$('button').remove(2)

but it is not working do you know other options to resolve this proplem?

CodePudding user response:

You can also use nth child selector

$("button:nth-child(2)").remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div>
  <button>1</button>
  <button>2</button>
  <button>3</button>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

.remove() accepts an optional selector, not an index.

If you're trying to remove the 3rd button (index 2), try narrowing the selection using .eq()

$("button").eq(2).remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js" integrity="sha512-6ORWJX/LrnSjBzwefdNUyLCMTIsGoNP6NftMy2UAm1JBm6PRZCO1d7OHBStWpVFZLO RerTvqX/Z9mBFfCJZ4A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div>
<button>1</button>
<button>2</button>
<button>3</button>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

or for multiple consecutive indexes, use .slice()

$("button").slice(0, 2).remove() // remove the first two

If you're trying to remove the button with text content "2", you can use the :contains() selector or use a more accurate .filter()

// $("button").remove(":contains(2)")

$("button").filter((index, el}) =>
  el.textContent.trim() === "2").remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js" integrity="sha512-6ORWJX/LrnSjBzwefdNUyLCMTIsGoNP6NftMy2UAm1JBm6PRZCO1d7OHBStWpVFZLO RerTvqX/Z9mBFfCJZ4A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div>
<button>1</button>
<button>2</button>
<button>3</button>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related