Reputation: 4572
Here's the fiddle
Within a looping function I will get html strings that have a span
element either at the top level or also it could be as a child within a div
. How can I find it in either case?
I know find
only searches children. Not even sure how to find it when it is in the top level, as in data2
below? If I did, then I guess I'd do a find
first, and if it's length was 0, then do the search for the span
in the top level.
var data1 = "<div class='form-group'><span class='editableColumn'>NAT</span><input type='text' class='editableColumn form-control' style='display:none' name='Lot' value='NAT'></div>";
var data2 = "<span class='editableColumn'>Yes</span><input type='checkbox' name='IsBackorder' class='editableColumn editor-active' style='display:none' checked='checked' value='true'>";
var myStringArray = [data1, data2];
var arrayLength = myStringArray.length;
$(document).ready(function() {
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
var span = $(data1).find("span.editableColumn").text();
$("#" + i).text(span);
}
})
Upvotes: 0
Views: 135
Reputation: 450
If your HTML had parents, you could do: $(myStringArray[i]).parent().closest("span.editableColumn").text();
Since you don't, you either need to wrap your data2 in a , or try find then closest:
$(document).ready(function() {
for (var i = 0; i < arrayLength; i++) {
console.log();
//Do something
var span = $(myStringArray[i]).find("span.editableColumn").text();
if (!span) span = $(myStringArray[i]).closest("span.editableColumn").text();
$("#" + (i + 1)).text(span);
}
})
Also, watch out: You've got i=0, < arrayLength, so it would only run through 0 and 1, and you have your ID's as 1 & 2, hence the $("#" + (i + 1))
Upvotes: 1
Reputation: 114
You can use .addBack() to do it in one line if you prefer that.
$(document).ready(function() {
for (var i = 0; i < arrayLength; i++) {
var span = $(myStringArray[i]).find("span.editableColumn").addBack("span.editableColumn").text();
$("#" + i).text(span);
}
})
Upvotes: 1