简体   繁体   中英

How do I remove HTML elements with specific attribute value?

I need to remove a tags with specific attribute value from a div tag.

This is for example:

<div id='testdiv'>
    <a dir='hello' href='#' ></a>
    <a dir='how' href='#' ></a>
    <a dir='which' href='#' ></a>
</div>
<input type='button' id='btn' />

Here is my jQuery:

$('#btn').click(function(){
   if($("#testdiv").find("a[dir='hello']").length == 1)
   {
       $("#testdiv").remove("a[dir=hello]");
   }
}

But its not working. What change shall I need to do with my jQuery?

try this:

$("a[dir=hello]").remove();

Here's the documentation

$('#btn').click(function(){
   $("#testdiv").remove("a[dir='hello']");
})
  • You need no if .
  • You forgot the quotes in the remove statement.
  • You forgot the last ) .

尝试这个:

$('a[dir="hello"]').remove

It's working:

$(function(){
        $('#btn').click(function(){
                if($("#testdiv").find("a[dir='hello']").length=='1'){
                    $("#testdiv").find("a[dir='hello']").remove();
                }
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM