1

I have a list of items

<div id="item1">somestuff</div>
<div id="item2">somestuff</div>
<div id="item3">somestuff</div>

When someone clicks on one of these, I need to take some actions based on the id (the number). Let's say hide it.

How can I make the function generic, and how can I pass the id into the function?

$(document).ready(function()
{
$("#item-howcanImakethisselectorgeneric?").click(function () { 
  $("#item-andhowcanIpasshteidintohere?").hide();
}
}

I'm a javascript/jquery newbie, any help (including rtfm) appreciated.

2 Answers 2

1
<div id="item1" class="mygenericClass">somestuff</div>

<div id="item2" class="mygenericClass">somestuff</div>

<div id="item3" class="mygenericClass">somestuff</div>
$(document).ready(function() 
{ 
  $(".mygenericClass").click(function () {  
    //if you want the id then $(this).id
    //if you just want to hide the clicked element then
    $(this).hide(); 
  }); 
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. How can I get the id without the "item" text, ie. just the number?
var justTheNumber = ($(this).id).replace("item", "")
0

try this:

<div id="item1" class="stuff">somestuff</div>
<div id="item2" class="stuff">somestuff</div>
<div id="item3" class="stuff">somestuff</div>

JS:

$(document).ready(function()
{
   $("#item1, #item2, #item3").click(function () { 
     $(this).hide();
   }
}

or even better:

$(document).ready(function()
{
   $("div.stuff").click(function () { 
     $(this).hide();
   }
}

or this if you will be dynamically adding more divs into the page after loading and don't want to explicitly add the event handlers

$(document).ready(function()
{
   $("div.stuff").live("click", function () { 
     $(this).hide();
   }
}

2 Comments

if you need to get the actual text of the id within the function, you can use "this.Id"
awesome. And to get only the number, so not "item1" but just "1"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.