pyronaur
pyronaur

Reputation: 3545

jQuery doesn't find by ID

I think Google Chrome console log is going to explain my problem best:

>> $(".single.portfolio")
[<article id=​"#js-single-item" class=​"post-883 portfolio type-portfolio status-publish hentry single">​…​</article>​]

>> the_element_id = $(".single.portfolio").attr("id")
"#js-single-item"

>> $(the_element_id)
[]

>> $("#js-single-item");
[]

>> document.getElementById("#js-single-item");
<article id=​"#js-single-item" class=​"post-883 portfolio type-portfolio status-publish hentry single">​…​</article>​

The weird thing is that getElementById works, but jQuery doesn't.

I tried to reproduce the problem in a fiddle by copying the whole HTML over and the code works as it's supposed to, so no trouble there. Most likely something is clashing together.

I'm looking for debugging tips. Thanks!

Edit: Typo. Problem Solved.

Upvotes: 2

Views: 2839

Answers (2)

Prakash GPz
Prakash GPz

Reputation: 1523

You have # at the beginning of the id. since # is the selector for 'id' in jQuery, it will consider, it as element with id = js-single-item not #js-single-item

Upvotes: 1

Ry-
Ry-

Reputation: 225238

id=​"#js-single-item"

The id attribute shouldn't include the # sign. When you select $('#some-id') in jQuery, it's actually calling document.getElementById('some-id').

You can do this:

$('#\\#js-single-item')

Also, don't.

Upvotes: 11

Related Questions