-2

I have an html block like this:

<div class="main">
    <div class="content">
    <h3><a href="/dir/dir/dir/?id=33" title="name">name</a></h3>
    <a href="/dir/dir/dir/?id=33" title=""><img src="/default.png" alt="name" /></a>
    </div>
</div>

I need to catch the id value (here 33) from the first <a href> tag.

My code is:

function getID(s){
    var s = $(this);
    var a = s.('a:first').attr('href').split('=');
    console.log a[1];
}

However console.log is returning me:

Uncaught SyntaxError: Unexpected token (

any idea?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
breteuil
  • 1
  • 1
  • 1
    `s.(` is invalid, and that is not printed by `console.log`. Your code is just not valid JavaScript, it is not executed because the parser cannot even parse it. – Felix Kling Feb 13 '12 at 10:59
  • should you use console.log as a function? console.log(a[1]); – trembon Feb 13 '12 at 10:59
  • thanks felix, I deleted "." which gives me var a = s('a:first').attr('href').split('='); but does not return me any id... – breteuil Feb 13 '12 at 11:54
  • @breteuil: It wouldn't because `s("a:first")` doesn't make much sense. It's the same as `$("a:first")`. How is your function `getID` called? What is `this` in it? – RoToRa Feb 13 '12 at 12:35

2 Answers2

2

Here’s a simple jQuery plugin:

$.fn.getID = function() {
  return this.prop('href').split('=')[1] || '';
};

Use it as follows:

$('a').first().getID(); // '33'
Sharon
  • 919
  • 7
  • 7
0

You can try:

function getID(){
    var theId = $('h3 a:first').attr('href').split('=')[1];
}

The ":first" is not mandatory as you only have one element in your element.

Valentin D
  • 705
  • 7
  • 14