0

This is probably something easy but I'm not having any luck even figuring out where I'd begin. The idea is I have a page that I am lading jquery overtop of...the jquery will look for links in tables, get the href (or more specifically part of the url since they link to elements on the same page) and then search for elements by the name so I can manipulate them. Or if any of you can think of a better way of doing it.

In other words what I hope to do is use the info from the URLS of the links to find the elements...I hope I've made myself clear...>.>

Eli
  • 14,779
  • 5
  • 59
  • 77
Harvengure
  • 21
  • 1
  • 3
  • So you are trying to use the links in your table to find elements with the same `name=''` as any one of the links in that table? – mattsven Apr 04 '11 at 04:46

3 Answers3

1

Use .attr('href'); to get the target.

http://jsfiddle.net/HfqDn/2/

S L
  • 14,262
  • 17
  • 77
  • 116
0

I'm guessing you want to do something like:

<table>
  <tr><td><a href="/items/1/order">Item 1</a></td></tr>
  <tr><td><a href="/items/2/order">Item 2</a></td></tr>
</table>
<script>
$('table tr').each(function () {
  var id = $('a', this).attr('href').match(/^\/items\/(\d+)\/order$/)[1];
  $(this).append('<td><a href="/items/'+id+'"/edit">Edit</a></td>');
});
</script>

This will append a new table cell to each row with a link to edit the appropriate item. You can do whatever you like with the id, so you could do something like $('#item-'+id).text('replaced!') instead.

If you're not familiar with regular expressions (the "/items/1/order".match(/^\/items\/(\d+)\/order$/)[1] bit) you should read up about them.

sj26
  • 6,725
  • 2
  • 27
  • 24
0

This should do what you specified

$().ready(function() {
    // For each link in any table
    $('table a').each(function(i) {
        // determine the anchors name
        var name = $(this).attr('href').match(/#(.*)$/)[1];
        // Select all anchors with name that matches the #<name>
        // We use the selector a[name="<name>"], double quotes are 
        // used to protect from white space characters in links
        var target = $('a[name="' + name +  '"]');
        // manipulate
        target.html('lorem ipsum dolor sit amet');
    });
});

Instead of relying on a regular expression, if you are able to modify the page, you could insert additional attributes to the links that contains the class name or the id of the element where the anchor is. Browsers do give you lots of liberties in adding extra attributes to elements that are not specified in the HTML standard. HTML5 even allows them, see Custom attributes - Yea or nay?.

Basically the custom attributes are ignored while rendering but they are added to the DOM nonetheless. When they reside in the DOM, you can access and use them however you want to.

Community
  • 1
  • 1
Aleksi Yrttiaho
  • 8,266
  • 29
  • 36