Alexey Tseitlin
Alexey Tseitlin

Reputation: 1339

jQuery beginner ".each()"

Why do I get an error in the console? "Uncaught SyntaxError: Unexpected token ;"

jQuery:

$("#menu a").each(function(){ 
console.log(($this.attr("href"));
});

HTML:

<body>
<div id="menu">
    <ul>
        <li class="selected"><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="contact.html">Contact</a></li>
        <li><a href="support.html">Support</a></li>
        <li><a href="faqs.html">FAQs</a></li>
        <li><a href="events.html">Events</a></li>
    </ul>
</div>

Upvotes: 0

Views: 60

Answers (5)

Dhiraj
Dhiraj

Reputation: 33628

It should be $(this) and not $this.

And also you have an extra parentheses opened inside console.log

Something like this

$("#menu a").each(function(){ 
  console.log($(this).attr("href"));
});

Upvotes: 1

prototype
prototype

Reputation: 3313

$this will return that kind of error since it's not defined while $(this) refers to each individual link (<a href="#">) and will work just fine.

Upvotes: 0

lshettyl
lshettyl

Reputation: 8181

Simply use this.href

$("#menu a").each(function(){
    //to grab the absolutel URL
    console.log( this.href );
    //To get the string from href
    console.log ( $(this).attr("href") );
});

Upvotes: 0

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Try this Working Demo

$("#menu ul li a").each(function(){ 
console.log(($(this).attr("href")));
})

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

You have mis-matched brackets, and $this should be $(this):

$("#menu a").each(function(){
    console.log($(this).attr("href"));
});

Upvotes: 4

Related Questions