除了span元素之外,删除div中的所有内容

时间:2018-04-16 07:37:11

标签: jquery

如何删除ID为null的div中的items字词?我想删除除span元素之外的所有内容。



$('#items').contents(':not(span)').remove();

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="items" class="w3-xxlarge" ><span class="glyphicon glyphicon-certificate w3-xxlarge w3-text-blue"></span>null</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

一个选项是使用html()并传递仅返回<span>

的函数参数

&#13;
&#13;
//Replace all contents with the span.
$('#items').html(function(){
     return $(this).find('span'); 
});
&#13;
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="items" class="w3-xxlarge" ><span class="glyphicon glyphicon-certificate w3-xxlarge w3-text-blue"></span>null</div>
&#13;
&#13;
&#13;

如果您只想删除 null

文本

&#13;
&#13;
$('#items').html(function() {
  return $(this).html().replace('null', '');
});
&#13;
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="items" class="w3-xxlarge"><span class="glyphicon glyphicon-certificate w3-xxlarge w3-text-blue"></span>null</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试类似

的内容

&#13;
&#13;
var html = $(' #items > *');//get elements except the text in the #items div
$('#items').html(html);//append them back to the element 
&#13;
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="items" class="w3-xxlarge" ><span class="glyphicon glyphicon-certificate w3-xxlarge w3-text-blue"></span>null</div>
&#13;
&#13;
&#13;