I'm using a function to add strings to an array from a textArea in a modal, then printing them to the DOM with innerHTML (which I learned here). The function is called with a button on the modal.
function setArray( ){
let textAreaElement = document.getElementById('textToArray');
let listArray = textAreaElement.value.trim().split('\n');
console.log(listArray);
document.getElementById('PrintToSidebar').innerHTML = listArray.join("<p>");//I want to add IDs in the <p> tags created here
modal.style.display = "none";
}
That seems to be working well, but I also want to set an ID for each individual <p>
, with the IDs being equal to the string values.
For example, if listArray = ["Line 1", "Line 2"], then my desired innerHTML would result in:
<p id="line-1">Line 1</p>
<p id="line-2">Line 2</p>
My searches seem to indicate I need to use the setAttribute method. But I'm also thinking I need to loop through listArray first.
I'm only a few days into Javascript (totally new to coding actually) so a detailed solution would be really helpful. Thank you!