How to make an attribute selection for the "(this) attribute starting with the #"

It might have been really late at night, but I couldn't figure it out. First the html:

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

      

in order to do something on the page and not navigate to a link, I need to filter it based on if it contains a # at the beginning. This is a perfect problem for solving [attribute ^ = value], but it doesn't work ...

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

      

I just know it is a problem with how to compose this attribute and attribute attribute ... and I don't know what to put after .val () ?!

+1


source to share


4 answers


I'm a little confused that you are exactly ...

if you want to check if the current object has # at the beginning of the href attribute:

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

      



Otherwise, you can do something like this:

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

      

+1


source


// using the following you are looking for all children that have an href tag starting with '#' inside 'this'



 var links = $('*[href^=#]', this); 

      

+1


source


I'm going to assume that what you are trying to extract is the content of the href attribute in the link, and you already know the container with the links.

I suggest that you want:

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

      

In this example, the array ['#internal', '# internal2'] should be returned. If this is not what you want, you can show what you expect from link

after your request.

+1


source


Sorry guys, as if I said that it is now in the fog from my late night. The simple answer was to move [href ^ = #] to the selector before trying to set the variables. It's my mistake for truncating it to a large amount, and my messy mind for filtering inside a variable, not a selector ... Thanks, although I couldn't do it without reading your (correctly) confused answers. Here's what I would normally work with big sleep:

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

      

thank

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

+1


source







All Articles