How to add string to jQuery selector?

I am trying to select an identifier that changes to different posts on the same page. Thus, they were assigned id = "show_posts_ {PostID}" - at the final output {PostID} is replaced by a number. In the function I need to call $('show_posts_XXXXXX') - XXXXXX - the generated identifier. I saved this identifier in a variable called postId.

But I can not do this $("'" + "show_posts_" + postId + "'")

Can someone tell me how can I add a line to the end of the selector?

+7
jquery string css-selectors
source share
4 answers

Must work. If this happens, you will kick yourself. Do not forget the hash for the identifier, and additional quotation marks are not needed.

 $("#show_posts_" + postId) 
+10
source share

You need to indicate the character "#" at the beginning of the line.

 $('#show_posts_' + postId) 

Also, you are trying to write quotes in your example, and that doesn't make sense.

+2
source share

just use $("#show_posts_"+postID)

+2
source share

Two things.

  • To select an element with a given ID, you need the # symbol at the beginning of the identifier.

  • Do not add quotation marks at the beginning and end of a line.

Thus:

 $('#show_posts_' + postId) 
+1
source share

All Articles