0
retVal.push($("<option>", { value: "thing1", text: "thing2" }));

I know it returns a JQuery<HTMLElement> object but I'm not sure of an elegant way of doing this that doesn't involve string concatenation.

For reference, I'm iterating over an object of KeyValuePairs and dynamically building a collection of options for a select html element.

Edit: full current code

ctl.append(ConvertStatusToDropdownItems());
...
var StatusEnum = { "thing1": 0, "thing2": 1, etc. };

function ConvertStatusToDropdownItems() {
var retVal = [];
for (const [key, value] of Object.entries(StatusEnum)) {
    retVal.push($("<option>", { value: value, text: key }));
}
return retVal;
}

For what it's worth, I'm technically inside a Typescript file in a .Net Core 2.1 site and can't seem to get the definitions for JQuery to load. And on further reflection, it's probably not a good idea to do so given the global nature of this function.

user4593252
  • 3,496
  • 6
  • 29
  • 55

1 Answers1

1

Using JavaScript we can create a helper function that assists us in replicating the functionality of the JQuery method.

let create = (tag, opts = {}) => {
  return Object.assign(document.createElement(tag), opts); 
}

let create = (tag, opts = {}) => {
  return Object.assign(document.createElement(tag), opts); 
}

console.log( 
  create("option", { value: "thing1", textContent: "thing2"})  
);

Note There is no such thing as a text property on a normal DOM node, only textContent.

zfrisch
  • 8,474
  • 1
  • 22
  • 34