user893182
user893182

Reputation: 97

Change the content of <a> inside <td> for every row in <table>

I have a large table, each row has 6 columns. Each row looks like this with different value:

<tr>
<td>year</td>
<td><a href="2012/some_file_path.pdf" target="_blank">Some Title</a></td>
<td>subject</td>
<td>catego</td>
<td>Department</td>
<td>name</td>
</tr>

I want to use jQuery to replace the text in <a> ("some title" in this case) with its path:

<tr>
<td>year</td>
<td><a href="2012/some_file_path.pdf" target="_blank">2012/some_file_path.pdf</a></td>
<td>subject</td>
<td>catego</td>
<td>Department</td>
<td>name</td>
</tr>

It's like a debugger for me to verify if I have all the files.. but I have no idea how to do it. Any help would be appreciated!


I have something like this in mind, but I don't really know the syntax:

function debug(){
    $('#datatable').find('tr').each
      $path = $('td:first-child + td > a').getHref();
      $('td:first-child + td > a').set($path);  
}

Upvotes: 0

Views: 2606

Answers (1)

Paul D. Waite
Paul D. Waite

Reputation: 98896

jQuery objects have an each() function, which allows you to supply a function to be run once for each DOM element that matches the jQuery object’s selector.

Assuming this is the only table on the page, and the table doesn’t contain any links other than the ones you want to change, this should do it:

$('table td a').each(function(){
    // Within a function passed to each(), “this” refers to the DOM element for 
    // which the function is being run.
    $link = $(this);

    $link.text($link.attr('href'));
});

Upvotes: 2

Related Questions