How to use a for
loop for document.getElementById
to copy multiple by one click of the submit button?
In the ID section:
a1
copy tob1
a2
copy tob2
a3
copy tob3
a4
copy tob4
function transferData() {
// Get the content of the first blockquote
var content1 = document.getElementById('a1').innerText;
// Set the content of the second blockquote
document.getElementById('b1').innerText = content1;
}
first
<blockquote contenteditable="true" id="a1"><p>text1</p></blockquote>
<blockquote contenteditable="true" id="a2"><p>text2</p></blockquote>
<blockquote contenteditable="true" id="a3"><p>text3</p></blockquote>
<blockquote contenteditable="true" id="a4"><p>text3</p></blockquote>
second
<blockquote contenteditable="true" id="b1"><p></p></blockquote>
<blockquote contenteditable="true" id="b2"><p></p></blockquote>
<blockquote contenteditable="true" id="b3"><p></p></blockquote>
<blockquote contenteditable="true" id="b4"><p></p></blockquote>
<button type="button" onclick="transferData()">Submit</button>
2
Answers
Assuming I’ve understood your goal correctly, then the simplest way to achieve this would be to wrap each set of
blockquote
elements in a container. You can then relate them directly to each other by index. This will remove the need to have any other identifiers on them.Pros: lightweight HTML which requires no knowledge of JS implementation. Simple logic.
Cons: requires the same number of source elements as target, so could be broken by a careless update to the HTML.
If, for whatever reason, you did not wish to relate them by index, then you could use a
data
attribute to set the target by itsid
:Pros: robust and extensible if you need to change the target element selectors
Cons: additional HTML required to target the correct elements.
Both will work, it depends on your exact use case as to which is the bext fit for you.
Here, we’re getting all elements that have an
ID
starting witha
, such asa1
.Then, we loop over all of those and add its
innerText
to theblockquote
that has anid
ofb + index
, whereindex
is the index of the loop operation. (We plus 1 since array indexes start at 0).This has downfalls. It assumes everything is in order, it assumes there’s an equal amount of a’s and b’s and it also assumes these elements are the only elements on the page, but it should be a good starting point.