简体   繁体   中英

Take the value of a child element

I have this structure:

<td class=​"prd-var-price">
    ​<div class=​"price-total">​
        <span class=​"price-unit">​€​</span>
        ​<span class=​"price-value">​
            <span class=​"price-value-int">​1.760​</span>
            ​<span data-decimalseparator=​"," class=​"price-value-cent">​,00​</span>​
        </span>
    ​</div>​
</td>​

when I write in the console:

a.getElementsByClassName("prd-var-price")

I would to take the value of price-value-int element (1760), I tried with:

$(a.getElementsByClassName("prd-var-price").getElementsByClassName("price-value-int"));

but this not work.

getElementsByClassName returns an array of elements, if you want only the first one (and in your example - you do) you should use a.getElementsByClassName("prd-var-price")[0].getElementsByClassName("price-value-int")[0]

but since you are using jQuery, a simpler approach would be:

 $('.prd-var-price .price-value-int');

jQuery uses css selector syntax to grab elements, you'll still get an array if more then one of this class structure exists

You might have multiple td with same class.

Better to use parent > child selection with find()

$('.prd-var-price').find('.price-value-int').text();

In each()

$('.prd-var-price').each(function(){
   console.log($(this).find('.price-value-int').text());
});

 $('td.prd-var-price').each(function(key, value){ console.log($(this).find('.price-unit').text()); console.log($(this).find('.price-value-int').text()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="prd-var-price"> <div class="price-total"> <span class="price-unit">€</span> <span class="price-value"> <span class="price-value-int">1.760</span> <span data-decimalseparator="," class="price-value-cent">00</span> </span> </div> </td> <td class="prd-var-price"> <div class="price-total"> <span class="price-unit">@</span> <span class="price-value"> <span class="price-value-int">2.760</span> <span data-decimalseparator="," class="price-value-cent">00</span> </span> </div> </td> </tr> </table> 

You can use jQuery FIND function to achieve your Goal

$(".prd-var-price").find(".price-value-int").text();

Demo

最好使用$('.prd-var-price .price-value-int)而不要使用$(a.getElementsByClassName("prd-var-price").getElementsByClassName("price-value-int"));

By using JQuery:

$("tr.prd-var-price").find('div.price-total span.price-value span:first-child").text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM