user1043646
user1043646

Reputation:

jQuery creating element names

Hey weird question but I am writing some code and I want to clean it up... The code goes as follows...

function (item){
    if(item == "1")
        $('div').show();
    if(item == "2"
        $('div1').show();
}

I tried something like

function (item)
   var $div = div+item;
   $($div).show()

Thanks

Upvotes: 3

Views: 50

Answers (2)

kubetz
kubetz

Reputation: 8556

There are several errors in your code.

  • 2nd if statement is missing )
  • you are trying to find <div1> element

There is no div1 element. If you want to refer element IDs you must use "#" so it becomes $('#idofthediv').

Your code is a bit confusing and it is not clear if you want to search for IDs, element names or it is mixed.

If you want to search for IDs div and div1 then just rename 1st id to div0 and the code will get cleaner (or better div1 and div2):

function (item) {
  $("#div" + (item - 1)).show(); 
}

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

function (item){
    $("#div" + (item > 1 ? (item - 1) : "")).show();
}

Assuming you mean #div + n, since div1 is not a valid selector. However, the logic should be the same no matter what the prefix of your actual selector is.

Example: http://jsfiddle.net/XXSTy/

For information on the conditional operator, check this MDN article.

Upvotes: 4

Related Questions