Search code examples
javascriptprototypejs

JS Prototype use a class within a class


<td class="a-right">
  <span class="price-excl-tax">
    <span class="price">$299.00</span>
  </span>
  <br>
</td>

I have the above code in HTML being generated. I need to use JS Prototype to get the value of the inner span. There are multiple spans with the class of "price", but only this one is nested inside of the class "price-excl-tax".

http://prototypejs.org/doc/latest/Prototype/Selector/

this is what I have:

console.log("Base price is: " + $$('price-excl-tax')[0].$$(span.price[0]).value);

Solution

  • Just as Barmar mentioned, use $$() with a CSS Child Selector (though a basic Descendant Selector would work as well) like '.price-excl-tax > .price'.

    See this illustrated in the example below. Note that it utilizes Event.observe() for the dom:loaded event (unique to PrototypeJS) to ensure the DOM is loaded before querying it. Also note that the innerHTML property is used to get the contents of the price element, though .textContent could also be used if there are no nested HTML nodes.

    document.observe("dom:loaded", function() {
      var priceContainers = $$('.price-excl-tax > .price');
      if (priceContainers.length) { //Greater than 0
        console.log("Base price is: " + priceContainers[0].innerHTML);
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.js"></script>
    <table>
      <tr>
        <td class="a-right">
          <span class="price-excl-tax">
        <span class="price">$299.00</span>
          </span>
          <br>
        </td>
      </tr>
    </table>

    An alternate approach would be to use Element.select(). Something like:

    var priceExclTaxContainers = $$('.price-excl-tax');
    if (priceExclTaxContainers.length) { //not empty
        var priceContainers = priceExclTaxContainers.select('.price');
        if (priceContainers.length) {
              //utilize priceContainers[0].innerHTML
        }
    }