0

i got a simple qiestion, i want to show and hide my divs according to their idies, but couldnt figure out, for example i have a different divs and inputs with different ids:

<input onfocus="showtip(1)" onblur="hidetip(1); />
<div id="tip1"></div>
<input onfocus="showtip(2)" onblur="hidetip(2); />
<div id="tip2"></div>

and

function showtip(id) {
    $('.tip[id]').show('slow');
}
function hidetip(id) {
    $('.tip[id]').hide('slow');
}

i can write it in javascript, to make it work, but i cant hide it with animation, thus i used jquery, but i can't define ids :( thank you all for the help! i really appreciate it!

2
  • To select by id use #: $("#elementId").show(); - is that what you're asking? Commented May 21, 2012 at 11:12
  • Hiya, you are trying is .class_name try #id_name and please go to this site and read some basic docs.jquery.com/Main_Page Commented May 21, 2012 at 11:12

3 Answers 3

2

To use the id attribute in jQuery use the id selector :

$('#<yourid>').show('slow');

so your method would be :

function showtip(id) {
   $('#tip'+id).show('slow');
}

(Note: ids should be unique across the whole document so no need to include the div bit in the selector)

If you id attributes contained characters such as . which means other things (ie a class selector) then you can use the attribute equals selector :

$('[id="123.abc"]').show('slow')
Sign up to request clarification or add additional context in comments.

4 Comments

yes :) u're mind reader o_0 i didnt finish qeuestion but u already answered it )) lol
sorry but @sudhir was first ) anyway +1
But what if your id attribute contains a ' or " character? ;)
@Domenic then you need a good talking too !!! :-) Something I would never put in the id attribute ... would cause no end of problems
1

You mean:

function showtip(id) {
    $('#'+tip).show('slow');
    //OR
    $('yourElement[id="'+tip+'"]').show('slow');
}

Comments

1

@ManseUK's method is by far the most common. But it is technically incorrect, as for example it will fail for id's containing characters that have other meanings in CSS, like .. The most correct solution is:

function showTip(id) {
    $(document.getElementById(id)).show("slow");
}

// This will work:
<div id="abc.123"></div>
showTip("abc.123");

This solution is also very slightly faster, since internally that's what jQuery would translate $("#" + id) to (in the cases where it works).

How this works:

  • document.getElementById(id) gets the raw DOM node.
  • $(...) wraps a raw DOM node in a jQuery object, which has jQuery methods like show.

1 Comment

+1 for being technically correct :-) and updated my answer with an example of using the attribute equals selector

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.