1110
1110

Reputation: 6829

Can't find element with jquery

I have a list of p tags on the page with id's like:

item_1
item_2
item_3
etc.

In jquery function I build string for id and than I want to change some value on it but it seams that jquery can't find element with this id, but it's there on the page:

...
var itemId = '#item_' + itemId;
                            if ($(itemId).length > 0) {
                                alert("exist");
                            }
...

Id is fine in itemId variable. Am I doing something wrong here maybe my approach is wrong? Markup

<div>
       <a href="#"><p id="item_283">Counter</p></a>
</div>

Upvotes: 1

Views: 2433

Answers (5)

Hadi Mostafapour
Hadi Mostafapour

Reputation: 2266

var itemId = '#item_' + itemId; // #item_+ << what +?
if ($(itemId).length > 0) {
   alert("exist");
}

Upvotes: 0

pankil thakkar
pankil thakkar

Reputation: 411

if($('#item_'+itemId))
{
alert('exist');
}

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

You seem to have some sort of variable scope clash, caused by overuse of the var keyword.

See this fiddle - http://jsfiddle.net/alnitak/acGmQ/ in which I've declared an outer itemId, and then inside a function I've replicated your code.

Inside that function the original itemId from the outer scope is no longer available, it's undefined, so you end up with #item_undefined.

Instead, write:

var sel = '#item_' + itemId;
if ($(sel).length > 0) {
    alert("exist");
}

Upvotes: 4

Ashray Baruah
Ashray Baruah

Reputation: 1595

Did you try:

var item = $('#item_'+itemId); if(item.length > 0).... 

?

Upvotes: 1

Pheonix
Pheonix

Reputation: 6052

var itemId = '#item_+' + itemId;

note the _+

thats not right

Upvotes: 1

Related Questions