如何检查嵌套标签的内容是否存在

How to check if the content of the nested tags exists or not

本文关键字:是否 存在 标签 嵌套 何检查 检查      更新时间:2023-09-26

假设我在div

中有一个这样的结构
<div class="mainDiv">
    <div class="addrLabel">Address</div>
<div class="addrValue">
<!-- this content value i want to check if exist, then grab it else no value -->
the content which i want to check if exist or not.  if a single value is there i want to grab it also
  <span class="hrefClass">
      <a href="#">next link</a>
  </span>
</div>
<div class="clearfix"></div>

第二次使用null值重复这个div

<div class="mainDiv">
    <div class="addrLabel">Address</div>
<div class="addrValue">
<!-- no value at all -->
  <span class="hrefClass">
      <a href="#">next link</a>
  </span>
</div>
<div class="clearfix"></div>

如何实现这个

试试这个演示…检查contents() div.addrValuenodeType是否为3 or a text node

var addrArray = [];
$(".addrValue").each(function(ndx, elem) {
  var text = $(elem).contents()
    .filter(function() {
      if (this.nodeType === 3) { // chech for text node
        if ($(this).text().trim().length !== 0) {
          return true;
        }
      }
    }).text();
  if (text.length === 0) { // check string length
    addrArray.push('no value at all');
  } else {
    addrArray.push(text.trim());
  }
});
console.log(addrArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainDiv">
  <div class="addrLabel">Address</div>
  <div class="addrValue">
    <!-- this content value i want to check if exist, then grab it else no value -->
    the content which i want to check if exist or not. if a single value is there i want to grab it also
    <span class="hrefClass">
      <a href="#">next link</a>
  </span>
  </div>
  <div class="clearfix"></div>
</div>
<div class="mainDiv">
  <div class="addrLabel">Address</div>
  <div class="addrValue">
    <span class="hrefClass">
      <a href="#">next link</a>
  </span>
  </div>
  <div class="clearfix"></div>
</div>

可以检查.text()是否等于false。这样的:

var addrArray = [];
if($('.addrValue').text() != false)
{
    addrArray.push($(this).text());
}else{
    addrArray.push('no value present');
}

检查小提琴:https://jsfiddle.net/ur5fntvp/

编辑
您也可以使用.html()方法代替.text()。这取决于你是想获取所有HTML标签还是只获取文本

$( document ).ready(function() {
 var a  = $('.addrValue').text()
 
 if(a.length) {
   console.log('exists')  
 } else {
   console.log("doesn't exists")  
 }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainDiv">
    <div class="addrLabel">Address</div>
<div class="addrValue">
<!-- this content value i want to check if exist, then grab it else no value -->
the content which i want to check if exist or not.  if a single value is there i want to grab it also
  <span class="hrefClass">
      <a href="#">next link</a>
  </span>
</div>
<div class="clearfix"></div>