views:

177

answers:

4

Maybe it's the really late night I had but I can't figure this one out. First the html:

<div>
<a href="#internal">Internal Link</a>
<a href="http://external.com"&gt;External Link</a>
<a href="#internal2">Internal Link2</a>
</div>

in order to do something on the page instead of going to the link I need to filter it based on if it contains a # at the start. It's the perfect problem for the [attribute^=value] solution but this doesn't work...

var link = $(this[href^=#]);

I just know it's an issue with how to put this and the attribute qualifier together... and I don't know what to put afterwards .val()?!

+1  A: 

I'm a little confused by what you're after exactly...

if you want to test if the current object has a # at the start of its href attribute:

var link = $(this);
if (link.is("[href^='#']") ...

Otherwise you could do something like this:

$('div a[href^="#"]').val("This link starts with a #");
nickf
+1  A: 

//using the following, you're searching all children that have an href tag starting with '#' inside of 'this'

 var links = $('*[href^=#]', this);
Andrew Theken
+1  A: 

I'm going to guess that what you are trying to extract is the contents of the href attribute on the link and you already know the container with the links.

I suggest that what you want is:

var link = $('a[href^=#]',this).attr('href');

This should return the array [ '#internal', '#internal2' ] in your example. If that's not what you want, you may want to show what you expect link to look like after your query.

tvanfosson
+1  A: 

Sorry guys - like I said I am in a haze at the moment from my late night. The simple answer was to move the [href^=#] to the selector before I try and establish variables. It's my fault for trimming it down to much and my messed up mind for trying to filter inside the variable and not on the selector... Thank you though and I couldn't have done it without reading your (rightly) confused replies. Here is what I would have normally worked out myself with more sleep:

$("div a[href^=#]").click(function() {
  var link = $(this).attr("href");
  ...

Thanks

ps. I have been trying to solve another problem all day today and I was considering posting it but after this I think I will go home, sleep, think about it fresh in the morning :D