7null 7null - 3 years ago 66
jQuery Question

jQuery loop through object and look for title but skip others

I have been teaching myself JS and Jquery and I still struggle with how to effectively use $ to loop through an object and extract the info I want.

I have a table that has a flag icon and a title describing that I want to put at end of the row. However, there are sometimes other icons that I must ignore. So I look for "flag" in url and if it exist I set innerHTML of 2nd to last cell to 'title'.

As you can see below I have had to create a decrement VAR y to keep from skipping to next row with "title" if I encounter non flag icon.

I want this row to be appended with "title" which is the location:

<td>11:44pm</td><td><a href="/stats/visitors?site_id=66351439&amp;date=2011-04-27&amp;country=the+united+states"></a></td><td> <a class="custom" title="Comcast Cable" href="/stats/visitors?site_id=66351439&amp;date=2011-04-27&amp;ip_address=75.70.103.23">Comcast Cable</a></td><td><a href="/stats/visitors-actions?site_id=66351439&amp;date=2011-04-27&amp;session_id=228613269">1 action</a></td><td>10s</td><td width="100%"> &nbsp; </td><td></td>


To look like this:

<td>11:44pm</td><td><a href="/stats/visitors?site_id=66351439&amp;date=2011-04-27&amp;country=the+united+states"></a></td><td> <a class="custom" title="Comcast Cable" href="/stats/visitors?site_id=66351439&amp;date=2011-04-27&amp;ip_address=75.70.103.23">Comcast Cable</a></td><td><a href="/stats/visitors-actions?site_id=66351439&amp;date=2011-04-27&amp;session_id=228613269">1 action</a></td><td>10s</td><td width="100%">Aurora, CO, USA</td><td></td>


So my question - What is a better way to do this whole procedure. Here is a link to the jsfiddle - http://jsfiddle.net/ukJxH/78/ - at 3:47 you can see a non flag icon.

var x = $('.tableborder tr img');
y = 1;
for (i = 0; i < x.length; i++) {
var flagg = x[i].src;
var pattn = /flag/gi;
var loca = x[i].title;

if (flagg.match(pattn) == "flag") {
//$('td:nth-child(6)')[i + 14 + y].innerHTML = loca;
$('#main :nth-child(i) td:nth-child(6)')[i].innerHTML = loc } else {
y = y - 1;
}


}

Answer Source

I'm sorry but I'm not sure I understand your question too well. However, the following selector will give you all the flags in the table

$('.tableborder tr img[src*="flag"]').each(function(){
   $(this)
    .closest('td')
    .nextAll('td:last')
    .html('Title from image : ' + $(this).attr('title'));
});

This should give you a chance to traverse the DOM and get at what you need

Live demo : http://jsfiddle.net/jomanlk/ukJxH/87/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download