user5405873 user5405873 - 1 month ago 9
jQuery Question

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

suppose i have a structure like this in my 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>




second time i am repeating this div with null value

<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>




how can i achieve this

Answer

try this demo... it checks if the nodeType of the contents() div.addrValue is 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>