To get the options you have just change the selector of the Jquery for $("#test>option")
that picks up all the labels <option>
within the <select>
test.
However for in your case it is much easier to get the html of <select>
whole and use in the placement within the <div>
:
$('#dv').append('<select name=' + algumName + '>' + $("#test").html() + '</select>');
Notice I also put some +
that were missing in select name='algumName'
Example:
let algumName = "nome";
$("button").click(function() {
$('#dv').append('<select name=' + algumName + '>' + $("#test").html() + '</select>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test" name "algumName">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button>Copiar opções</button>
<div id="dv">
</div>
Closest
This server function to scroll the DOM tree up and pick up the nearest element that plays with the nominee. Search begins in the element itself.
In the code you used, $(this).closest('#test')
, would catch the element #test
if above, but still not solving the problem.
Illustrating a simple use of closest
:
$("#p1").closest("h1").css('background-color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
<p id="p1">texto p1</p>
</h1>
Here $("#p1").closest("h1")
catches the <h1>
closest to <p>
, which is exactly above.
html can be more complex than closest
tried in the same to catch some element, going through all the elements above until reaching the top:
$("#p1").closest("div").css('background-color','red');
div {
height:150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>
<p id="p1">texto p1</p>
</h1>
</div>
In this last example was made the closest
for a <div>
, trying to catch the <div>
closest to <p>
which is what is two levels up. We can see that it was the one where the color was assigned due to the larger size that was given in this example.
He’s trying to get the
<options>
within the<div>
?– Isac
yes, I made a change in the codes of my question, to better understand
– Gislef
is just what I want to do see this part of the code:
append($('<select name='algumName'>"+ options +"</select>'));
– Gislef
Yes I was writing the moment I was changing
– Isac
@Gislef you only want the html of the options? for example, <option value="1">1</option>...?
– haykou