I have multiple <div>
elements, and they have 3 things in common (<h3>
, <textarea>
, <img>
). On a button click, I need to get a JSON result (shared below).
Here is what I have tried, but I'm unable to convert to JSON, but I am able to convert it to separate arrays.
function get_json() {
var groups = Array.from(document.querySelectorAll(".StackedList"));
var imgs = groups.map(function(group) {
return Array.from(group.querySelectorAll("img")).map(function(item) {
return new URL(item.src).pathname.substring(1);
});
});
var desc = groups.map(function(group) {
return Array.from(group.querySelectorAll("textarea")).map(function(item) {
return item.value
});
});
var h3text = groups.map(function(group) {
return Array.from(group.querySelectorAll("h3")).map(function(item) {
return item.innerText
});
});
alert(imgs + desc + h3text)
return imgs, desc, h3text
}
<div class="StackedList" id="group1">
<h3 id="c1" style="display:inline" contenteditable="true">Item 1</h3>
<textarea id="desc1" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/10.jpg" />
<img class="draggable" src="http://localhost:99/11.jpg" />
<img class="draggable" src="http://localhost:99/12.jpg" />
</div>
<div class="StackedList" id="group2">
<h3 id="c2" style="display:inline" contenteditable="true">Item 2</h3>
<textarea id="desc2" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/8.jpg" />
<img class="draggable" src="http://localhost:99/7.jpg" />
<img class="draggable" src="http://localhost:99/2.jpg" />
</div>
<div class="StackedList" id="group3">
<h3 id="c3" style="display:inline" contenteditable="true">Item 3</h3>
<textarea id="desc3" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/1.jpg" />
</div>
<input type="button" value="Get json" onclick="get_json()">
Expected output
I need to get JSON on a button click.
{
"Item 1": {
"descrption": "Entered text value",
"images": ["10.jpg", "11.jpg", "12.jpg"]
},
"Item 2": {
"descrption": "Entered text value",
"images": ["8.jpg", "7.jpg", "2.jpg"]
},
"Item 3": {
"descrption": "Entered text value",
"images": ["1.jpg"]
}
}