Andrew Scott
asked on
How to traverse table element in jquery??
Hello I am new to jquery. I want to traverse this table .
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.
<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>
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
In this specific case you could use this mix of jQuery and then pure JS:
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.
var pricediv;
pricediv = $('.price').clone().children('div')[0];
while (pricediv.firstChild.nextSibling) {
pricediv.removeChild(pricediv.firstChild.nextSibling);
}
alert(pricediv.innerHTML);
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:
Bye, Olaf.
var pricediv;
pricediv = $('.price').children('div')[0];
text = pricediv.innerHTML;
alert(text.substr(0,text.indexOf('<')));
Bye, Olaf.
Julian answered the author's question with a pure jQuery solution.
Open in new window