Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting text content of a div element excluding its children

I have the following HTML code and I need to console.log only Shipping. I tried a few methods but can't seem to get it to work. I tried selecting first its children and printing out the textContent of its parent - no go. I could delete its children and print out what's left but I can't do that.

Any suggestions?

<div class="accordion shadowed-box shipping collapsed summary">
  <fieldset>
    <legend>
    Shipping
        <div id="shippingTooltip" class="form-field-tooltip cvnship-tip" role="tooltip">
          <span class="tooltip">
            <div class="tooltip-content" data-layout="small tooltip-cvn">
              <div id="cart-checkout-shipping-tooltip" class="html-slot-container">
                <p>We ship UPS, FedEx and/or USPS Priority Mail.<br>  
                  <a class="dialogify" data-dlg-options="{&quot;height&quot;:200}" href="https://www.payless.com/customer-service/ordering-and-shipping/cs-ordering-shipping-schedule.html" title="shipping information">Learn more about our shipping methods and prices.</a>
                </p>    
              </div> 
            </div>
          </span>
        </div>
      <a href="javascript:app.checkout.editShipping();" id="section-header-note-sa" class="section-header-note" style="display: inline;">Edit</a>
    </legend>
  </fieldset>
</div>

I tried this:

var accordionChildren = document.querySelector('.accordion.shadowed-box.shipping>fieldset>legend *');//selects the first child
var accordionTitle = accordionChildren.parentElement;
var text = accordionTitle.textContent;
console.log(text);

I want to get Shipping but instead I get still all the text contents of the legend element.

like image 284
Yann B Avatar asked Oct 31 '25 00:10

Yann B


1 Answers

you can access Text nodes by iterating over the child nodes (or access the intended node directly) of the accordionTitle variable.

let textNode = accordionTitle.childNodes[0],
    text = textNode.textContent;

console.log(text);

See https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes and https://developer.mozilla.org/en-US/docs/Web/API/Text

like image 76
mexn Avatar answered Nov 01 '25 14:11

mexn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!