简体   繁体   English

如何删除具有特定属性值的HTML元素?

[英]How do I remove HTML elements with specific attribute value?

I need to remove a tags with specific attribute value from a div tag. 我需要删除a从具有特定属性值的标签div标签。

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: 这是我的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? 我需要对jQuery做哪些更改?

try this: 尝试这个:

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

Here's the documentation 这是文档

$('#btn').click(function(){
   $("#testdiv").remove("a[dir='hello']");
})
  • You need no if . 你不需要if
  • You forgot the quotes in the remove statement. 您忘记了remove语句中的引号。
  • 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();
                }
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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