room_id_div is not a valid html-element. You can create an element and assign some properties to it in one go using Object.assign. If you want to use the id within the innerText of the created element, you'll have to create the (random) id separately.
Alternatively you can set the content of a div using a pseudo-selector in css (:before). In that case you don't need to create a random id separately. The downside is that the text within the div can not be selected (hence, not copied to the clipboard).
Both demonstrated in this snippet:
document.addEventListener("click", handle);
document.addEventListener("change", handle);
function handle(evt) {
const origin = evt.target;
if (/Room$/.test(origin.id)) {
return origin.id === "fromIdRoom" ?
createRoom1() : createRoom2();
} else if (origin.id === "roomSelector") {
if (origin.value !== "-1") {
document.querySelectorAll("#roomId1 div")
.forEach(elem => elem.style.backgroundColor = "");
document.querySelector(`#${origin.value}`).style.backgroundColor = "#FFFFC0";
}
}
}
// room id from css pseudo :before
// use [makeId] directly
function createRoom1() {
const roomParent = document.querySelector("#roomId1");
roomParent.append(
Object.assign(
document.createElement("div"), {
id: `X${makeId(15)}`, // NOTE: id can not start with a number
})
);
const idNow = roomParent.querySelector("div:last-child").id;
roomParent.querySelector("select").append(
Object.assign(
document.createElement("option"), {
value: idNow,
textContent: idNow
})
);
}
// room id within innerText
// you'll need to pre-assign [room]
function createRoom2() {
const room = `X${makeId(15)}`; // NOTE: id can not start with a number
document.querySelector("#roomId2").append(
Object.assign(
document.createElement("div"), {
id: room,
innerText: `Room id: ${room}`,
})
);
}
function makeId(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
#roomId1 div:before {
content: 'Room id from css: 'attr(id);
}
<p>
<button id="fromIdRoom">create create a room within #roomId1</button>
<button id="createRoom">create a room within #roomId2</button>
</p>
<div id='roomId1'>
<select id="roomSelector">
<option value="-1">Select room</option>
</select>
</div>
<div id='roomId2'></div>