Austin
Austin

Reputation: 406

jquery selector with variable does not find element

I have this line of code

$("#ir-area-name").html(list);

That works just fine, but I need to move this into a function that can be called for any id, and every answer I have seen says I can run it like this:

$("#"+variable_name).html(list);

where variable_name is a string containing the id. But, this isn't working for me, it doesnt find any element and no error message is printed. When printing the contents of the selector to console they both print the value [object Object]. However, when running it with the variable the element dissapears from screen (as it apparently didn't find the element so it never ran html()). For testing purposes I tried it like this as well:

$("#"+"ir-area-name").html(list);

But this still didn't find the element. So the question is how can I use a variable in a jquery selector (using jquery 1.7.1, testing on firefox).

Upvotes: 0

Views: 450

Answers (1)

Rich Flavell
Rich Flavell

Reputation: 436

You should use string concatenation.

$("#" + ir-area-name).html(list)

Or using ES6 string substitution syntax (docs)

$(`#${ir-area-name}`).html(list)

If the element is found, the html of the element will be replaced with the contents of list.

Upvotes: 1

Related Questions