P
P
Pavel Martynov2010-12-20 09:15:43
JavaScript
Pavel Martynov, 2010-12-20 09:15:43

jQuery how to find all links on current page?

Goal: Find all links in the given div that point to the current page.

I wrote this selector

$('div#top_menu a[href="' + document.URL + '"]')


but it doesn't find anything, because links in divs are relative (/>),
while document.URL is an absolute link ( localhost/account/page.aspx ).

Here is a query that produces the necessary absolute reference:

$('div#top_menu a[href="page.aspx"]')[0].href


But how can I query this property?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
L
lashtal, 2010-12-20
@xkrt

Filter through each:
$('div#top_menu a').each(function(){
if (this.href='xxxxxxxx') { %do_something% }
});

P
Pavel Martynov, 2010-12-20
@xkrt

Thank you all very much, most of all I need the solution of the habrauser, here is a reworking of his solution that suited me:

$(document).ready(function () {
  $('div#top_menu a').each(function(){
    if (this.href == document.URL) {
      $(this).addClass('b-menu_current');
    }
  });
});

PS: jquery 1.4.1

O
omfg, 2010-12-20
@omfg

Perhaps you just need to take the last piece of the url?

$('div#top_menu a[href="' + document.URL.substring(document.URL.lastIndexOf("/")+1,document.URL.length) + '"]')

And in your case (c [0]), you take the js object, not jquery, and look at its href property (by which you made the selection)

A
Alexander Belugin, 2010-12-20
@unkinddragon


$(function(){
   var path = location.pathname.substring(1);
   if ( path )
     $('div#topmenu a[href$="' + path + '"]').attr('class', 'selected');
 });

S
shsmad, 2010-12-20
@shsmad

document.location.pathname to help you

N
nikitammf, 2010-12-20
@nikitammf

Solve in reverse order. Those. take all the links inside the given div and filter them by href so that the current link is the ending for document.URL, even jQuery is not needed here

var links = document.getElementById('myDiv').getElementsByTagName('a'),
      result = [], $result;
for(var i = links.length - 1, j = 0; i > -1; i--) {
    if( document.URL.indexOf(links[i].href) + links[i].href.length != document.URL.length ) { continue; }
    result[j++] = links[i];
    $result = $result.jquery ? $result.add(links[i]) : $(links[i]);//результат как jquery объект
}

But there is a small “but”, for example, “mysite/” and “mysite/index.html” point to the same page, with all the nuances that follow

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question