Reputation: 917
Below is the sample td for a dynamic table generated.
I need to iterate through the tds to match the 'Data'
values and to check if its corresponding 'Result'
value is populated or not.
If the 'Result'
is not populated , there will not be span class="taglist"
element.
<td class="indent0">
Data1
<span class="aspect-data">
<span class="taglist">Result1</span>
</span>
<td class="indent0">
Data2
<span class="aspect-data">
<span class="taglist">Result2</span>
</span>
I have tried to iterate using the below code, which alerts all the 'Result'
values, but I need to get only the corresponding values of a 'Data'
given.
$('.indent0').each(function() {
var celltext = $(this).html();
if (celltext = "Data1") {
var spantext = $(this).find(".taglist").html();
if (spantext != null) {
alert(spantext);
}
}
});
Upvotes: 1
Views: 1917
Reputation: 337560
The issue you have is that DataX
is not wrapped in a specific element, so you'll need to grab the text node and check the text value of that against the value you're looking for.
Also note that you're using =
for setting a value instead of ==
to compare a value in your if
condition, and your HTML is missing some </td>
tags. Try this:
$('.indent0').each(function() {
var celltext = $(this).contents()[0].nodeValue.trim();
if (celltext == "Data1") {
var spantext = $(this).find(".taglist").html();
if (spantext != null) {
alert(spantext);
}
}
});
Upvotes: 2
Reputation: 20740
You can use startsWith()
like following.
$('.indent0').each(function () {
var celltext = $(this).text().trim(); // change here
if (celltext.startsWith("Data1")) { // change here
var spantext = $(this).find(".taglist").html();
if (spantext != null) {
alert(spantext);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="indent0">
Data1
<span class="aspect-data">
<span class="taglist">Result1</span>
</span>
</td>
<td class="indent0">
Data2
<span class="aspect-data">
<span class="taglist">Result2</span>
</span>
</td>
</tr>
</table>
Upvotes: 1
Reputation: 68383
try using contents
$('.indent0').each(function() {
var celltext = $(this).contents().first()[0].textContent; //this line has changed
if (celltext == "Data1") {
var spantext = $(this).find(".taglist").html();
if (spantext != null) {
alert(spantext);
}
}
});
or
$('.indent0').each(function() {
var celltext = $(this).contents()[0].nodeValue; //this line has changed
if (celltext == "Data1") {
var spantext = $(this).find(".taglist").html();
if (spantext != null) {
alert(spantext);
}
}
});
Upvotes: 1