Jerry Svensson Jerry Svensson - 5 months ago 10
Javascript Question

Target text in element without targeting the child element strings

I need to target the word "Apple" in the html below with the script below, but it will target all the strings inside the parent container. How do I target the text that isn't wrapped? One solution would be to wrap the text in its own child first, but unsure how to target it that way.

ccs_cc_args.push(['FFR_NAME', $(".infobar").text()]);


HTML:

<div class="infobar">
<center><img src="" alt="image"></center>
<span>Manufacturer</span>Apple<span>Part Number</span>
<div class="productboxArticlenumber">MC723-US-4-500-REF</div>
</div>

Answer

var a = $('.infobar').contents().filter(function(){
    return this.nodeType == 3;
}).text();

console.log(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="infobar">
 <center><img src="" alt="Apple"></center>
 <span>Manufacturer</span>thisistheAppletext<span>Part Number</span>
 <div class="productboxArticlenumber">MC723-US-4-500-REF</div>
</div>

  1. Use node type == 3 meaning text.
  2. Use .contents

Description: Get the children of each element in the set of matched elements, including text and comment nodes.