Filipe Ferminiano
Filipe Ferminiano

Reputation: 8791

Access table cell with javascript in chrome console

I have this table and I want to access the prod_sku value and define it as a variable:

<tr class="border first last" id="order-item-row-386470">
<td><h3 class="product-name">prod_name</h3>
</td>
<td data-rwd-label="SKU">prod_sku</td>
<td class="a-right" data-rwd-label="Preço">
    <span class="price-excl-tax">
    <span class="cart-price">

        <span class="price">prod_price</span>                    
    </span>


    </span>
    <br>
</td>
</tr>

I get this table with this line:

data = document.getElementsByClassName("odd")[0].innerHTML;

From this tbody

<tbody class="odd">
<tr class="border first last" id="order-item-row-386470">
<td><h3 class="product-name">prod_name</h3>
</td>
<td data-rwd-label="SKU">prod_sku</td>
<td class="a-right" data-rwd-label="Preço">
<span class="price-excl-tax">
<span class="cart-price">
<span class="price">prod_price</span>                    
</span>


</span>
<br>
</td>
<td class="a-right" data-rwd-label="Qtd">
<span class="nobr">
Solicitado: <strong>1</strong><br>
</span>
</td>
<td class="a-right last" data-rwd-label="Subtotal">
<span class="price-excl-tax">
<span class="cart-price">

<span class="price">prod_price</span>                    
</span>


</span>
<br>
</td>
</tr>
</tbody>

How can I access prod_sku?

Upvotes: 0

Views: 1231

Answers (3)

dreadnought
dreadnought

Reputation: 133

var data = document.querySelector('td[data-rwd-label="SKU"]').innerHTML;

But would be more interesting to improve the html structure of your table.

Upvotes: 0

Barmar
Barmar

Reputation: 781878

You can use a query selector to match the data-rwd-label attribute.

document.querySelector('td[data-rwd-label=SKU]').innerHTML

Upvotes: 2

JohanP
JohanP

Reputation: 5472

If you don't have to support stone age browsers, then you can use querySelector to grab your td based on data attribute. If you have to support a myriad of outdated browsers and you need to d a lot of these types of lookups, then jquery is quite good at it.

Upvotes: 2

Related Questions