Home > Software engineering >  Create dictionary entry with key, value for each Div javascript
Create dictionary entry with key, value for each Div javascript

Time:10-14

<div id="divholder">
  {%for i in volcanoinfo%}
    <div >
      <p id="volcanoname" style="display: none;">{{ i['name'] }}</p>
      <p id="volcanolat" style="display: none;">{{ i['vlat'] }}</p>
      <p id="volcanolon" style="display: none;">{{ i['vlng'] }}</p>
    </div>
  {%endfor%}
</div>

Firstly, the divs are produced as above using a json file I am then looking to produce a dictionary where it contains Name, latitude and longitude for each div.

I have tried running a for loop in a dictionary but dont really know what I'm doing. Is it possible to create this dictionary? I have an array created using

  var div = document.getElementById('divholder');
  var volcdiv = div.getElementsByTagName('p')
  var divs = div.getElementsByTagName('div');
  var divArray = [];

  for (var i = 0; i < divs.length; i  = 1) {
    divArray.push(volcdiv[i].innerHTML);
    console.log(divArray)
  }

So I know it is possible to retrieve all the data. Is there a way to now form this dictionary? Cheers

CodePudding user response:

Try to loop through the divs and get each value using query selector and push the result as an object to the result array

  var div = document.getElementById('divholder');

  var divs = div.getElementsByClassName('volcdiv');
  var divArray = [];

  for (var i = 0; i < divs.length; i  = 1) {
    console.log(divs[i])
    var volcanoname = divs[i].querySelector('[id="volcanoname"]').innerHTML
    var volcanolat = divs[i].querySelector('[id="volcanolat"]').innerHTML
    var volcanolon = divs[i].querySelector('[id="volcanolon"]').innerHTML
    divArray.push({"volcanoname":volcanoname, "volcanolat": volcanolat, "volcanolon": volcanolon });
  }
  document.getElementById("result").value = JSON.stringify(divArray);
<div id="divholder">
    <div >
      <p id="volcanoname" >1</p>
      <p id="volcanolat" >11</p>
      <p id="volcanolon" >111</p>
    </div>
        <div >
      <p id="volcanoname" >2</p>
      <p id="volcanolat" >22</p>
      <p id="volcanolon" >222</p>
    </div>
    <input type="text" id="result"/>
</div>

https://jsfiddle.net/uwdczrh0/2/

  • Related