My task is to extract the information from a webpage, display all the headings as categories in a dropdown menu, and then map all the sentences within each heading to their respective category

I've been tasked with extracting information from a webpage and organizing it into categories for a dropdown menu. Each category will have associated sentences listed underneath. For example, let's say we have a webpage structured like this:

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

My goal is to parse this webpage and create a dropdown menu with options for 'Fruit,' 'Animal,' and 'Car.' When a category is selected, the corresponding sentences should be displayed.

Answer №1

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Establish characteristics for the temporary print document

Struggling to configure the properties of a temporary file created for later printing by the user. Here's a breakdown of the process: User clicks on "Print Map Area" button on the website. A menu appears asking for preferred dimensions (e.g. A4 ...

If the element contains a specific class, then replace the text within the element with a new set of words

Looking for a solution: <form id="new_user"> <div id="first-name"> <label for="user_profile_attributes_first_name"><abbr title="required">*</abbr> First name</label> </div> </form> I need to change the text ...

Can someone explain how to implement an onclick event for a div element inside an iframe using jquery or javascript?

Understanding the HTML Structure <iframe src="#" scrolling="no" id="gallery-frame"> <div class="gv_filmstrip"> <div class="gv_frame"> <div class="gv_thumbnail current"> <img src="images/grandstand-padang-right/1.jpg"> </d ...

Converting a JavaScript function to AngularJS: A step-by-step guide

Utilizing a plugin that employs this set of statements to showcase menus, I have now incorporated it into an AngularJS framework. (function(window) { 'use strict'; var support = { animations : Modernizr.cssanimations }, animEndEventNames = { ...

Issue with JavaScript's variable scoping

After testing my application, I found that the following code was originally working: var htm = "<div> My content </div>"; $("#divprint").html(htm); window.setTimeout('window.print()', 4000); However, when I attempted to enclose it ...

What steps should I take to resolve the XSS vulnerability in Django when using jQuery?

https://i.sstatic.net/FcWYq.jpg After writing this code for the message functionality using Ajax, I encountered an issue. Whenever I input <script>alert("Django+Ajax");</script> into the form and submit it, an alert pops up on my browser. I ...

Column overflowing from row in Bootstrap grid on smaller screens

Is there a way to rearrange the display order of my Hello-div-2 and Hello-div-3 on small screens? Currently, the sequence is Hello-div-1, Hello-div-2, Hello-div-3, Hello-div-4. It needs to be Hello-div-1, Hello-div-3, Hello-div-2, Hello-div-4. ...

Re-executing PHP script using AJAX on the existing webpage

I am facing a rather intricate issue. Currently, I am in the process of constructing a page that searches tags in a MySQL table and displays results without any reloading or redirection. The tags are user-input and managed using JavaScript. Let me outline ...

Identify the nature of the output received after dispatching

I'm developing a functional component within the realm of Redux, and I have configured it to return specific values for a particular action. The new value being returned is derived from a Promise, meaning that if the type is designated as "Ival," the ...

Hover over an element to trigger the background fading effect on the parent div

I'm looking to create a hover effect on an element within a fullscreen div. When I hover over the element, I want a background image to fade in on the div with the class ".section." While I can easily display the background image, I am unsure of how t ...

Error when testing React Material UI: TypeError - Attempting to read property 'get' of undefined

I encountered an issue with the following code snippet: /* eslint-disable react/display-name */ import { Box, Button, LinearProgress, makeStyles } from '@material-ui/core'; import { Refresh } from '@material-ui/icons'; import { SearchHi ...

Can anyone recommend a drag-and-drop feature in Javascript that functions seamlessly on both iPad and PC devices?

Can anyone recommend a JavaScript plugin that allows for drag and drop functionality on both touch and mouse enabled devices, including IOS, Android, PC, and Mac? For touch-enabled devices, I found an example here: And for mouse-enabled devices, there is ...

Unexpected appearance of blank space to the right of my parallax design

Ever since a forced reboot, my parallax scrolling page has been experiencing issues. A strange whitespace seems to be throwing off the sections, only appearing every other section - one is fine, the next is offset, and so on. I've carefully gone thro ...

What is the best way to integrate Handlebars with Express?

Understanding the question isn't tough, but I'm unsure about integrating handlebars with Express. This is my current code: var express = require('express'); var app = express(); app.get('/', function (req, res, next) { ...

Leveraging JavaScript within PHP script

I am currently developing a booking system that involves creating events in a table using PHP. I want to implement a script that will run when a user tries to book an event and then submits the form to PHP. This script will help me determine if the user ha ...

Error: Null object does not have a property 'split' to read from

Struggling to authenticate for Google API connection to utilize Google Analytics, I'm facing an issue with the following code: 'use strict' const fs = require('fs') const open = require('open') const Fs = require(&apos ...

Unable to prevent default behavior when submitting a form

I have been experiencing an issue where my HTML form reloads the webpage upon submission, despite including the e.preventDefault() command in my submission function. $("#room-code-form").addEventListener("submit", function(e) { e.preventDefault(); }); ...

Is it possible for the scroll event to be triggered while scrolling only when a div element is used?

While utilizing window.onscroll to track scroll events during scrolling, I noticed that in certain Android devices the scroll event is only triggered after the scroll has completed. However, when monitoring scroll events within a specific div element, it ...

Having difficulty displaying nested arrays in AngularJS

Understanding JSON Data in AngularJS As I delve into the world of AngularJS, I've encountered a minor roadblock when it comes to fetching JSON data. <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/boots ...

A Node.js feature that enables atomic file replacement, triggering watchers only once

I have a unique scenario where I need to handle two types of processes. One process is responsible for writing a file, while the other processes are required to read it whenever there is a change. In my research, I came across fs.watch as a solution to ke ...