Reputation: 3
I'm trying to make a simple messenger for my school project
I need to store id number of each chat message inside himself (which is a div tag) and I want to access this value from JavaScript with id or name of div.
sorry for my bad English
Upvotes: 0
Views: 1564
Reputation: 383
So what you want to use for storage is an array cause it's way faster than the DOM and the DOM isn't your storage. Here a small code example how to use an array to store stuff, extract and foreach
// declaring the array
const messages = [];
// can be automated to restructure incoming dataformat
function incoming(nodeId, msgId, msg) {
messages.push({
// you can store the html node directly for faster access
// even better if you pass the node as a parameter
// "node": document.getElementById(nodeId),
"node": nodeId,
"msgId": msgId,
"msg": msg
})
// do other stuff here example:
// appendMsg();
}
// incoming messages
incoming("box-1", 25823, "hi, whats up??")
incoming("box-2", 25824, "not much...")
incoming("box-3", 25825, "wanna learn JS?")
let searchResult = messages.find((ele) => {
// use return ele.node.id == `box-1` if you store the elements and want to find an element
return ele.node == "box-2"
})
console.log(searchResult)
// using map to print the text of all messages
messages.map(ele => console.log(ele.msg))
Upvotes: 0
Reputation: 168
Let assume a div tag's id equals to NumberID ( <div id="NumberID"></div>
)
If you are gonna wanna use javascript,
var NumberID = document.getElementById("NumberID").innerHTML;
Then you can get the result from the NumberID variable.
Upvotes: 1
Reputation: 538
You can store arbitrary data in custom attributes.
<div id="id1" any="value">
document.getElementById("id1").getAttribute("any");
Upvotes: 1
Reputation: 587
divID = 'the id of your div';
content = 'the content you want in that div';
div = document.getElementById(divID);
div.innerHTML(content);
Documentation:
Upvotes: 0