For example if I add a select with .append() and then I want to add options to that added select, how can I assign it to a variable while adding it?
The only way I've managed is to find it after adding it with the .find() method
$(this).append('<select></select>');
var select = $(this).find('select');
select.append($('<option>', {
value: 5,
text: 'texto',
))
I think this is not correct or I have not done something right
var select = $(this).append('<select></select>');
select.append($('<option>', {
value: 5,
text: 'texto',
))
I would like to know if there is any way to make it more elegant
What you're looking to do, having the element you're adding in a variable would be just the opposite of what you're doing.
The variable
this_
references the jQuery element$(this)
In this case the variable
select
refers to the created jQuery element . (Since these jQuery methods return the object itself).I would assign an id:
I think the problem with your code is putting
<select></select>
, you should only put<select>
, and it would look like this:Another way and it is a very understandable way would be the following: