7

I'm trying to select an id that changes on different posts of same page. So the they have been given an id="show_posts_{PostID}" - on the final output the {PostID} is replaced with a number. In the function I need to call $('show_posts_XXXXXX') - XXXXXX being the generated ID. I have stored this ID in a variable called postId.

But I can't seem to do this $("'" + "show_posts_" + postId + "'")

Can anyone tell me how I can add a string to the end of a selector?

2
  • 2
    You know what? I didn't even realize I had to do that. Thanks! Commented Apr 27, 2010 at 12:05
  • I personally don't think that the SO site makes that clear enough, but whatever. Glad to see that you've gotten the info you needed here. Commented Apr 27, 2010 at 12:20

4 Answers 4

10

Should work. If it does, you'll kick yourself. Don't forget the hash for the ID, and the extra quotation marks aren't necessary.

$("#show_posts_" + postId)
Sign up to request clarification or add additional context in comments.

2 Comments

You're right I am kicking myself. I started with exactly that. Then it wasn't working and I started second guessing. I realized that it wasn't the selector that I was having issues with! Thanks
No probs. We all make simple mistakes!
2

You need to include the '#' character at the start of the string.

$('#show_posts_' + postId)

Also, you're trying to stuff the quotes in there in your example, and that doesn't make sense.

1 Comment

I started with exactly that. Then it wasn't working and I started second guessing. I realized that it wasn't the selector that I was having issues with! Thanks
2

just use $("#show_posts_"+postID)

Comments

1

Two things.

  1. To select an element with a given ID, you need a # character at the beginning of the ID.

  2. Don't add the quotes to the beginning and end of the string.

Thus:

$('#show_posts_' + postId)

Comments

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.