如何删除 id items
div 内的null
字?我想删除除跨度元素以外的所有内容。
$('#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>
一种选择是使用 html()
并传递一个仅返回<span>
的函数参数
//Replace all contents with the span.
$('#items').html(function(){
return $(this).find('span');
});
<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>
如果只想删除文本 null
$('#items').html(function() {
return $(this).html().replace('null', '');
});
<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>
你可以尝试类似的东西
var html = $(' #items > *');//get elements except the text in the #items div
$('#items').html(html);//append them back to the element
<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>