I have a html page as below:
<div id="test1">
<table>
<tr>
<td><span id="234">ABKO</span></td>
</tr>
<tr>
<td><span id="1234">ABKO2</span></td>
</tr>
<tr>
<td><span id="2634">ABKO3</span></td>
</tr>
</table>
</div>
<div id="test2">
<table>
<tr>
<td><span id="233">ABKOw</span></td>
</tr>
<tr>
<td><span id="1236">ABKOc</span></td>
</tr>
<tr>
<td><span id="2635">ABKOv</span></td>
</tr>
</table>
</div>
How can i get all the span details between using jQuery?
eg if i consider first div=test1 then i want all the soan with their ID and text
as
div -> test1
Span => id 233 && ABKO
Span => id 1234 && ABKO2
Span => id 22634 && ABKO3
You can iterate through all the
<span>elements like so:You can see it in action here.
What this is doing is building a list of span elements that are nested in a div (CSS selector
div span). It then iterates over this list using the .each() method.Within each iteration
$(this)refers to the matched span element. We capture a reference in the$spanvariable so we don’t keep recreating the same jQuery object.We then use the .closest() method to find the span’s first ancestor that matches the given selector (
div). This gets our parent div.Finally .attr() and .text() gets the ID attribute and text values .