JQuery appending a drop down option reducing whitespace into one


I am trying to dynamically append a option in select list using jQuery:

let text1 = "jg";
console.log("length of text: " + text1.length);
$("#selectList").append($('<option>', {
    value: 12,
    text: text1
}));

This time it gives length of text: 7

Now I want to retrieve the selected text from select list but when I do that I get the text which has only one white space in the middle rest of the white space in between is truncated. The code I used to retrieve value from select list pasted below:

let e = document.getElementById("selectList");
let selected = e.options[e.selectedIndex].text;
console.log("text: " + selected);
console.log("selected length: " + selected.length);

Now the text is just j, g, and selected length: 3. How can I get the above 7 length long text from select list?

You need to use innerHTML instead of text:

let text1 = 'j     g';
console.log("length of text: " + text1.length);
$("#selectList").append($('<option>', {
    value: 12,
    text: text1
}));

let e = document.getElementById("selectList");
let selected = e.options[e.selectedIndex].innerHTML;
console.log("text: " + selected);
console.log("selected length: " + selected.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='selectList' ></select>

You can even use innerText instead of text:

let text1 = 'j     g';
console.log("length of text: " + text1.length);
$("#selectList").append($('<option>', {
    value: 12,
    text: text1
}));

let e = document.getElementById("selectList");
let selected = e.options[e.selectedIndex].innerText;
console.log("text: " + selected);
console.log("selected length: " + selected.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='selectList'></select>


You can use the .textContent DOM property of the select and you will avoid the whitespace normalization that naturally occurs when text is parsed as HTML.

But, since you are using JQuery, it doesn't make sense to mix and match vanilla DOM APIs when you're already using jQuery.

With jQuery, you can use the .text() method of element to get the same result.

let text1 = "j     g";
console.log("length of text: " + text1.length);

let $list = $("#selectList");
$list.append($('<option>', {
  value: 12,
  text: text1
}));

console.log("text: " + $list.text());
console.log("selected length: " + $list.text().length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectList"></select>