Link to home
Start Free TrialLog in
Avatar of Andrew Scott
Andrew Scott

asked on

How to traverse table element in jquery??

Hello I am new to jquery. I want to traverse this table .
<div id="compare">
    <table>
        <thead></thead>
        <tbody>
            <tr class="stock4">
                <td>
                    <img src="abc.jpg" alt="">
                </td>
                <td class="price">
                    <div>
                        1000
                        <div class="variant">
                            <table>
                                <thead></thead>
                                <tbody>
                                    <tr class="stock4">
                                        <td class="price">2000</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Open in new window



I want a  price only 1000 not 2000 from variant div.How can I do it. I have tried many procedure but I didnt succeed.
Avatar of Jim Riddles
Jim Riddles
Flag of United States of America image

If all you want to do is to change the price, it would look like the following:
$('div.variant table tbody tr.stock4 td.price').html('1000');

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In this specific case you could use this mix of jQuery and then pure JS:

var pricediv;
pricediv = $('.price').clone().children('div')[0];
while (pricediv.firstChild.nextSibling) {
  pricediv.removeChild(pricediv.firstChild.nextSibling);
}
alert(pricediv.innerHTML);

Open in new window


In the end, I would aim for more generic code removing the unwanted child sibling nodes to get to the core text value you want.
Julian's solution has to be preferred as pure jQuery. And in fact, I think you don't get around cloning.

What you need more generally depends on what the sub nodes could become in other examples, I think this could become more complex and so just removing all variant class child nodes would not suffice in the more general case.

What you need is the firstChild of the div without any sibling nodes. Not sure how to do this more elegantly in jQuery without falling back to JS with the initial jQuery nodes result.

Bye, Olaf.
You may also go the simple route of a substring of innerHTML:

var pricediv;
pricediv = $('.price').children('div')[0];
text = pricediv.innerHTML;
alert(text.substr(0,text.indexOf('<')));

Open in new window


Bye, Olaf.
Julian answered the author's question with a pure jQuery solution.