A guide on traversing through nested HTML divs using jQuery

I am facing an issue with nested HTML div elements on my website. The data is being fetched from a JSON file and stored in a variable.

For example, the 'obj' variable contains an array of objects with properties such as Name, Progress, Description, and Status. These can be accessed using the following syntax:

obj[index].Name
obj[index].Progress
obj[index].Description
obj[index].Status

I need to iterate over each div element and populate it with the corresponding data using jQuery.

For instance, I want to loop through each info-box inside the div(#row) and update the values within the specified HTML elements:

 - <span class="info-box-text">NAME-1</span>
 - <div class="progress-bar" style="width: 70%"></div>
 - <span class="progress-description">PRODUCT-DESCRIPTION-1                            </span>
-  <span class="label label-info">PROGRESS-1</span>

The jQuery each function should iterate through the following HTML structure:

<div class="row">
       <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box">
                <div class="info-box bg-yellow">
                    <span class="info-box-icon"><i class="ion ion-filing"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">NAME-1</span>
                        <div class="progress">
                            <div class="progress-bar" style="width: 70%"></div>
                        </div>
                        <span class="progress-description">
                            PRODUCT-DESCRIPTION-1
                        </span>
                        <span class="label label-info">PROGRESS-1</span>
                        <span style="padding-left:5px" class="ion-person-stalker">&nbsp;5</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box">
                <div class="info-box bg-green">
                    <span class="info-box-icon"><i class="ion ion-filing"></i></span> 
                    <div class="info-box-content">
                        <span class="info-box-text">NAME-2</span>
                        <div class="progress">
                            <div class="progress-bar" style="width: 85%"></div>
                        </div>
                        <span class="progress-description">
                         PRODUCT-DESCRIPTION-2
                        </span>
                        <span class="label label-success">PROGRESS-2</span>
                        <span style="" class="ion-person-stalker">&nbsp;8</span>
                    </div>
                </div>
            </div>
        </div>


        <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box">
                <div class="info-box bg-red">
                    <span class="info-box-icon"><i class="ion ion-filing"></i></span> 
                    <div class="info-box-content">
                        <span class="info-box-text">NAME-3</span>
                        <div class="progress">
                            <div class="progress-bar" style="width: 70%"></div>
                        </div>
                        <span class="progress-description">
                            PRODUCT-DESCRIPTION-3
                        </span>
                        <span class="label label-success">PROGRESS-3</span>
                        <span style="" class="ion-person-stalker">&nbsp;15</span>
                    </div>
                    <!-- /.info-box-content -->
                </div>
            </div>
        </div>
   </div>

Answer №1

If you're looking to extract properties from HTML into a JSON object, you can achieve this by following these steps: To see the results, please check the console.

$(function(){
  var obj = {};
  for(var i=0;i<$('.item').length;i++){
    obj[i] = {
      Name : $('.item').eq(i).find('.info-box-text').html(),
      Progress : $('.item').eq(i).find('.progress-bar').html(),
      Description : $('.item').eq(i).find('.progress-description').html(),
      Status : $('.item').eq(i).find('.status').html()
    }
    
  };
  console.log(obj);
  
})
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<div class="row">
       <div class="col-md-3 col-sm-6 col-xs-12 item">
            <div class="info-box">
                <div class="info-box bg-yellow">
                    <span class="info-box-icon"><i class="ion ion-filing"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">NAME-1</span>
                        <div class="progress">
                            <div class="progress-bar" style="width: 70%">70</div>
                        </div>
                        <span class="progress-description">PRODUCT-DESCRIPTION-1</span>
                        <span class="label label-info status">PROGRESS-1</span>
                        <span style="padding-left:5px" class="ion-person-stalker">&nbsp;5</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-3 col-sm-6 col-xs-12 item">
            <div class="info-box">
                <div class="info-box bg-green">
                    <span class="info-box-icon"><i class="ion ion-filing"></i></span> 
                    <div class="info-box-content">
                        <span class="info-box-text">NAME-2</span>
                        <div class="progress">
                            <div class="progress-bar" style="width: 85%">85</div>
                        </div>
                        <span class="progress-description">PRODUCT-DESCRIPTION-2</span>
                        <span class="label label-success status">PROGRESS-2</span>
                        <span style="" class="ion-person-stalker">&nbsp;8</span>
                    </div>
                </div>
            </div>
        </div>


        <div class="col-md-3 col-sm-6 col-xs-12 item">
            <div class="info-box">
                <div class="info-box bg-red">
                    <span class="info-box-icon"><i class="ion ion-filing"></i></span> 
                    <div class="info-box-content">
                        <span class="info-box-text">NAME-3</span>
                        <div class="progress">
                            <div class="progress-bar" style="width: 70%">70</div>
                        </div>
                        <span class="progress-description">PRODUCT-DESCRIPTION-3</span>
                        <span class="label label-success status">PROGRESS-3</span>
                        <span style="" class="ion-person-stalker">&nbsp;15</span>
                    </div>
                    <!-- /.info-box-content -->
                </div>
            </div>
        </div>
   </div>

Additionally, if you wish to append and add HTML elements based on your JSON object:

You can create a string of the div element you want to add using JavaScript. For instance, you can define a function like makeText which constructs the necessary HTML elements.

//for exmaple :
var obj = [
  {Name:'Name1',Progress:'Progress1',Description:'Description1',Status:'Status1'},
  {Name:'Name2',Progress:'Progress2',Description:'Description2',Status:'Status2'},
  {Name:'Name3',Progress:'Progress3',Description:'Description3',Status:'Status3'},
  {Name:'Name4',Progress:'Progress4',Description:'Description4',Status:'Status4'},
  {Name:'Name5',Progress:'Progress5',Description:'Description5',Status:'Status5'},
]

for( var x in obj){
$('.appendToHere').append(makeText(obj[x].Name,obj[x].Progress,obj[x].Description,obj[x].Status));
}

function makeText(Name,Progress,Description,Status){
return('<div class="col-md-3 col-sm-6 col-xs-12"><div class="info-box"><div class="info-box bg-yellow"><span class="info-box-icon"><i class="ion ion-filing"></i></span><div class="info-box-content"><span class="info-box-text">'+Name+'</span><div class="progress"><div class="progress-bar" style="width: 70%"></div></div><span class="progress-description">'+Description+'</span><span class="label label-info">'+Progress+'</span><span style="padding-left:5px" class="ion-person-stalker">&nbsp;'+Status+'</span></div></div></div></div>');
}
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<div class="row appendToHere"></div>

Answer №2

To ensure each "content box" or content part has a unique class name, it is necessary to make some adjustments. By adding specific classes to the main item boxes and the elements within them, you can easily iterate through them like this:

$('.itembox').each(function() {
    console.log($(this).find('.itemname').html()); --debug print
    // TODO here you can set/get or do want you want for each content value
    //$(this).find('.itemdecription')... etc
});

The key changes involve assigning the class "itembox" to each main item box, and using the class "itemname" for the span element containing the name. This pattern should be followed for other content elements such as descriptions.

For example:

       <div class="info-box itembox">
           <div class="info-box bg-yellow">
              <span class="info-box-icon"><i class="ion ion-filing"></i></span>
                <div class="info-box-content">
                   <span class="info-box-text itemname">NAME-1</span>
                     <div class="progress">
                       <div class="progress-bar" style="width: 70%"></div>
                     </div>
                     <span class="progress-description">
                         PRODUCT-DESCRIPTION-1
                     </span>
                     <span class="label label-info">PROGRESS-1</span>
                     <span style="padding-left:5px" class="ion-person-stalker">&nbsp;5</span>
                 </div>
             </div>
        </div>

Answer №3

Utilizing the brute force method depicted below is effective. It essentially iterates through each class and populates the corresponding data element. For more information, refer to jQuery.each()

However, if your dataset is expected to expand beyond 3 rows, employing templates (as recommended in the comments) would offer a more resilient solution.

Feel free to show and execute the snippet below:

function updateUI( data ) {

  $('.info-box-text').each(function(i, o) {
    $(o).html(data[i].Name || '');
  });

  $('.progress-bar').each(function(i, o) {
    $(o).html(data[i].Progress || '');
  });

  $('.progress-description').each(function(i, o) {
    $(o).html(data[i].Description || '');
  });

  $('.label').each(function(i, o) {
    $(o).html(data[i].Status || '');
  });

};

function updateUI( data ) {

  $('.info-box-text').each(function(i, o) {
    $(o).html(data[i].Name || '');
  });

  $('.progress-bar').each(function(i, o) {
    $(o).html(data[i].Progress || '');
  });

  $('.progress-description').each(function(i, o) {
    $(o).html(data[i].Description || '');
  });
  
  $('.label').each(function(i, o) {
    $(o).html(data[i].Status || '');
  });

};



$(document).ready(function() {
  
// generate test data
var i, data = [];
for (i = 0; i < 3; i++) {
  data.push({
    Name: 'Name-' + i,
    Progress: 'Progress-' + i,
    Description: 'Description-' + i,
    Status: 'Status-' + i
  });
}
  
  updateUI( data );
  
  window.debug.innerHTML = JSON.stringify( data, false, '  ');
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-3 col-sm-6 col-xs-12">
    <div class="info-box">
      <div class="info-box bg-yellow">
        <span class="info-box-icon"><i class="ion ion-filing"></i></span>
        <div class="info-box-content">
          <span class="info-box-text">NAME-1</span>
          <div class="progress">
            <div class="progress-bar" style="width: 70%"></div>
          </div>
          <span class="progress-description">
                            PRODUCT-DESCRIPTION-1
                        </span>
          <span class="label label-info">PROGRESS-1</span>
          <span style="padding-left:5px" class="ion-person-stalker">&nbsp;5</span>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-3 col-sm-6 col-xs-12">
    <div class="info-box">
      <div class="info-box bg-green">
        <span class="info-box-icon"><i class="ion ion-filing"></i></span> 
        <div class="info-box-content">
          <span class="info-box-text">NAME-2</span>
          <div class="progress">
            <div class="progress-bar" style="width: 85%"></div>
          </div>
          <span class="progress-description">
                         PRODUCT-DESCRIPTION-2
                        </span>
          <span class="label label-success">PROGRESS-2</span>
          <span style="" class="ion-person-stalker">&nbsp;8</span>
        </div>
      </div>
    </div>
  </div>


  <div class="col-md-3 col-sm-6 col-xs-12">
    <div class="info-box">
      <div class="info-box bg-red">
        <span class="info-box-icon"><i class="ion ion-filing"></i></span> 
        <div class="info-box-content">
          <span class="info-box-text">NAME-3</span>
          <div class="progress">
            <div class="progress-bar" style="width: 70%"></div>
          </div>
          <span class="progress-description">
                            PRODUCT-DESCRIPTION-3
                        </span>
          <span class="label label-success">PROGRESS-3</span>
          <span style="" class="ion-person-stalker">&nbsp;15</span>
        </div>
        <!-- /.info-box-content -->
      </div>
    </div>
  </div>

</div>


<h3>JSON:</h3>
<xmp id="debug"></xmp>

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

Retrieve the next element in android studio that shares the same class name as jsoup

i am trying to access the next element with the same class name in HTML. The HTML tag structure looks like this: HTML: <section class="post"> <img class="pecintakomik" src="/images/top/op.jpg" alt="pecintakomik.com" /> <div class=" ...

javascript execute while load

I'm having trouble initializing inputs with maps api autocomplete based on the number of inputs retrieved from the database. I'm trying to run a simple JavaScript function within a while loop, but it's not working as expected. Although the ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Dealing with VueJS - Sharing an array of data from a child to a parent component using v-model

I am facing an issue in emitting data (array) from a child component to a parent component using v-model. However, when the parent component is created, my console.log does not work. I am hesitant to work with Vuex as I am still a beginner. Here is my chi ...

Start a new typescript project from scratch

Seeking assistance in setting up a blank TypeScript project with a package.json, TypeScript and HTML file. I am looking for something akin to the Stackblitz blank-typescript project. If anyone could provide me with a step-by-step guide on how to create su ...

Different methods for modifying the height of an Angular datatable in response to the data provided

Encountering an issue with adjusting the height of a datatable when calling a webservice to populate it. A webpage features a collapsible div element alongside a datatable. Upon collapsing the div, the table's height is calculated and resized using i ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Exploring the internet using a specific font style and ensuring a

I am facing an issue with the fonts on my website. They work perfectly in all browsers when using http, but as soon as I switch to https, the fonts stop working in IE8 and lower versions. However, they do display correctly in ie9. When trying to access th ...

Changing directions while the script is running

For my web site testing, I created a script using Tampermonkey that randomly browses the site and modifies parameters. Sometimes I need to navigate to a different page by either using window.location.replace(URL) or by clicking a button with the script l ...

What is the best way to obtain the id of an HTML element that is generated within jQuery code?

Typically, data is retrieved in HTML by storing the html in the html file. In my case, however, I create the html element inside jQuery. So, how do I call out the div id? How can I replace document.getElementByID ("edit").innerHTML=.... when the element i ...

Tips for sending jQuery variable with an Ajax GET call?

I have a jQuery slider that generates values. Now, I need to pass these variables to a URL in the format using an Ajax get request. In my index.php file, I have the following JavaScript code which assigns values to the variables 'rich' and &apo ...

Chrome isn't showing the Background Image

I am currently working on coding a basic HTML/CSS page and I want to include a background-image within a div element that links to a URL. Interestingly, my code is functioning properly in Safari (Mac) and Firefox but unfortunately not showing the desired r ...

Challenges with the efficiency of hover effects

I have a div with a background image and inside that div, there is a component called Hero. I want to add a simple hover effect on a div with a className newBigButton. However, the transition is laggy when the background image is present. Here's the c ...

Just for laughs: "The react-redux context value seems to be playing hide and seek; make sure to wrap the component in a <Provider> for it to show up!"

I encountered an issue while attempting to run a basic Jest test on a form React component: ● <LoginForm /> › clicking the validate button › should display page title ...

Utilizing attributes as scope properties within AngularJS

I am currently working on a directive and I need to pass the Attributes (Attrs) to the $scope, however, I am facing some difficulties in achieving this. Specifically, my goal is to assign attributes in my template based on the name set in my date-picker ta ...

Sort the data by name rather than using the default JSON/C# format

On my webpage, I am displaying product data that is being called in the form of a JSON object in the JavaScript file: _loadAll: function (callback) { $.ajax({ 'type': 'GET', 'timeout': 5000, ' ...

Incorporate CSS styling within a PHP document

Many individuals are aware that HTML can be embedded within a PHP file. However, can CSS also be included in a PHP file and accessed using <link rel="stylesheet" type="text/css" href="mystyle.php" /> to make it act as a CSS file? While it is possib ...

Enhance the functionality of NodeJS core applications

I recently attempted to modify some custom functions in the FS module of NodeJS, which is an integral part of NodeJS' core modules. The specific file I targeted was fs.js, located in /usr/lib/nodejs. However, despite making changes to the code, I noti ...

Concealed div obstructing access to dropdown menu

I'm having some trouble creating a dropdown menu. The submenu I've created is appearing behind my wrapper, page, and content. I've attempted to adjust the z-index of various elements and have even tried setting the z-index of my menu and sub ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...