Begin by converting the text on the webpage into a JSON object.
Next, loop through the JSON Object to generate a select item
Here is the HTML Code snippet:
<div id="target">
Fruits:
Apple is a fruit
Mango is a fruit
Watermelon is a fruit
Animal:
Human is an animal
Cat is an animal
Dog is an animal
Car:
Ford is a car
Hyundai is a car
Audi is a car
</div>
<select name="category" id="category"></select>
<div id="output">Please select a category<div>
</div>
Javascript code snippet:
target=document.getElementById("target").innerHTML;
lines=target.split("\n");
json_array=[];
var obj={};
obj.name="";
obj.array=[];
for(i=0;i<lines.length;i++){
lines[i]=lines[i].replace(/^[ ]+|[ ]+$/g,'');
if(lines[i].indexOf(":")!=-1){
if(obj.name!=""){
json_array.push(obj);
obj=new Object();
obj.name=lines[i].replace(":","");
obj.array=[];
}
else
obj.name=lines[i].replace(":","");
}
else{
if(lines[i].length>0){
obj.array.push(lines[i]);
}
}
}
json_array.push(obj);
console.log(JSON.stringify(json_array));
menu=document.getElementById("category");
for(i=0;i<json_array.length;i++){
var opt = document.createElement('option');
opt.value = json_array[i].name;
opt.innerHTML = json_array[i].name;
menu.appendChild(opt);
}
menu.addEventListener("change", function() {
for(i=0;i<json_array.length;i++){
if(menu.value == json_array[i].name){
output.innerHTML="";
for(j=0;j<json_array[i].array.length;j++){
output.innerHTML+=json_array[i].array[j]+"<br>";
}
}
}
});
View Demo