I want to locate every child that appears after the <body> element, and extract the HTML of the element containing a specific class within it

It may sound a bit confusing at first, but essentially I have some dynamically generated HTML that resembles the following:

<body>
<div class="component" id="465a496s5498">
  <div class="a-container">
   <div class="random-div">
    <div class="wantThis">
      <div class="wantThisHTML">Hello!<p>I'm another element!</p></div>
    </div>
   </div>
   <div class="random-div">
    <div class="random"></div>
   </div>
  </div>
</div>
<div class="component" id="683fg5865448">
  <div class="another-container">
   <div class="random-div">
    <div class="wantThis">
      <div class="wantThisHTML">Wow!</div>
    </div>
   </div>
   <div class="random-div6">
    <div class="random2"></div>
   </div>
 </div>
</div>
<div class="component" id="247487294js5">
  <div class="more-containers">
   <div class="random-div">
    <div class="wantThis">
      <div class="wantThisHTML">Haha!</div>
    </div>
   </div>
   <div class="random-div6">
    <div class="random5"></div>
   </div>
 </div>
</div>
</body>

I am aiming to form an array of objects that contains the unique ID of each component and the raw HTML within the element with the class name "wantThis" (which will always be named "wantThis"). Therefore, the resulting array would appear as follows:

[{
 id: "465a496s5498",
 html: "<div class='wantThisHTML'>Hello!<p>I'm another element!</p></div>"
},{
 id: "683fg5865448",
 html: "<div class='wantThisHTML'>Wow!</div>"
},{
 id: "247487294js5",
 html: "<div class='wantThisHTML'>Haha!</div>"
}]

In terms of my approach, I've divided the elements into an array using var elements = $(body).children. I understand how to retrieve the HTML content of an element using $(.wantThis).html(), but I am unsure of how to extract both the ID and the HTML from each child element I obtain.

Additionally, there could be multiple elements within the wantThis element - will $(.wantThis).html() return the raw HTML of all the children?

Answer №1

Here is the solution.

var data = $('> .component', document.body).map(function(component) {
    return {
      id: this.id,
      html: $(this).find('.wantThisHTML').html()
    }
  })
  .toArray();

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="component" id="465a496s5498">
  <div class="a-container">
    <div class="random-div">
      <div class="wantThis">
        <div class="wantThisHTML">Hello!
          <p>I'm another element!</p>
        </div>
      </div>
    </div>
    <div class="random-div">
      <div class="random"></div>
    </div>
  </div>
</div>
<div class="component" id="683fg5865448">
  <div class="another-container">
    <div class="random-div">
      <div class="wantThis">
        <div class="wantThisHTML">Wow!</div>
      </div>
    </div>
    <div class="random-div6">
      <div class="random2"></div>
    </div>
  </div>
</div>
<div class="component" id="247487294js5">
  <div class="more-containers">
    <div class="random-div">
      <div class="wantThis">
        <div class="wantThisHTML">Haha!</div>
      </div>
    </div>
    <div class="random-div6">
      <div class="random5"></div>
    </div>
  </div>
</div>

Answer №2

When it comes to tackling this issue...

Begin by choosing the Nodes (elements) using "querySelectorAll"

const nodeListOfElements = document.querySelectorAll('.element')

This will give you a NodeList. NodeList

You can then convert this into an array of Nodes by:

const elementArray = [].slice.call(nodeListOfElements)
Stack Overflow Post

After that, utilizing that array of nodes. You can 'map' it to fit the desired structure.

const updatedResult = elementArray.map(function(item, index) {
  let targetElement = item.querySelector('.needThisHTML')
  return {
    id: item.id,
    html: targetElement.innerHTML
  }
})

Note: each "item" represents an element/node and the querySelector method can be utilized to choose children of that element. I am focusing on the specified class. After that, it's simply about generating an object for each loop iteration that the map function runs. You determine the keys and values that the map function outputs. In this case, I'm setting the id key to the element's id, and the html key to the "innerHTML" of the targeted child element within each primary element.

The resulting format appears as follows:

(3) [{…}, {…}, {…}]
0: {id: "465a496s5498", html: "Hello!<p>I'm another element!</p>"}
1: {id: "683fg5865448", html: "Wow!"}
2: {id: "247487294js5", html: "Haha!"}
length: 3

Explore the CodePen example: https://codepen.io/nstanard/pen/exOJLw

If you found this helpful, please consider giving an upvote and approving my answer! Thank you

Answer №3

Ensure that the .component contains the desired '.wantThis' child element.

var data = $('.wantThis').map(function() {
  return {
    id: $(this).parents('.component').attr('id'),
    html: $(this).html()
  }
});
console.log(data);

var data = $('.wantThis').map(function() {
  return {
    id: $(this).parents('.component').attr('id'),
    html: $(this).html()
  }
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="component" id="465a496s5498">
  <div class="a-container">
   <div class="random-div">
    <div class="wantThis">
      <div class="wantThisHTML">Hello!<p>I'm another element!</p></div>
    </div>
   </div>
   <div class="random-div">
    <div class="random"></div>
   </div>
  </div>
</div>
<div class="component" id="683fg5865448">
  <div class="another-container">
   <div class="random-div">
    <div class="wantThis">
      <div class="wantThisHTML">Wow!</div>
    </div>
   </div>
   <div class="random-div6">
    <div class="random2"></div>
   </div>
 </div>
</div>
<div class="component" id="247487294js5">
  <div class="more-containers">
   <div class="random-div">
    <div class="wantThis">
      <div class="wantThisHTML">Haha!</div>
    </div>
   </div>
   <div class="random-div6">
    <div class="random5"></div>
   </div>
 </div>
</div>

Answer №4

<div id="unique-elem">
    <div id="elem-description">Unique Element</div>
</div>

<script>
    alert(unique-elem); // DOM-element with id="unique-elem"
    alert(window.unique-elem); // accessing global variable like this also works

    // for elem-description things are a bit more complex
    // since it has a dash inside, it can't be a variable name in JavaScript
    alert(window['elem-description']); // ...but accessible using square brackets [...]
</script>

reference: https://javascript.info/searching-elements-dom

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

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Ways to eliminate the vertical scroll feature in a kendo chart

I am encountering an issue while loading a kendo chart inside grid-stack.js where I am unable to resize the height properly. Whenever I decrease the height, a vertical scroll appears which should not happen. I have tried setting the height to auto and refr ...

Encountering problems when trying to mock values with Jest

I'm currently integrating Jest into an existing project that is already utilizing enzyme and jasmine. Although I have installed the jest packages and configured them initially, I am facing an issue where the mock data is not being supplied correctly. ...

Upon inserting Node 5, an error with the code EINVALIDTYPE occurred in npm

Recently, after I upgraded to Node 5, I've been encountering an error in the terminal every time I try running anything with npm. npm -v: 2.14.12 Desperately attempting to update npm to the latest version: MacBook-Pro-de-MarceloRS:promo-auto-loan ...

Exploring the distinctions among different xpath implementations in Selenium WebDriver

Looking at this snippet of HTML code: <div id="divTooltips_Section_Filter" style="float:right; padding-right: 30px; padding-bottom: 10px;"> <img src="/mkteditor/css/images/tooltip.png" width="25px" height="25px" alt=""> </div> I've ...

Unable to establish API connection in node.js

As a novice, I recently delved into the world of APIs using node.js. My goal was to fetch data from a simple API for practice. This venture is just an experiment and any assistance or guidance on connecting to APIs, especially those requiring an API key, ...

Positioning an HTML control on top of a Silverlight Application, ensuring it moves in sync with the application as it scrolls

   I am facing a challenge with my Silverlight Application (VS2010/C#) that runs in full screen mode.    There is also an HTML control positioned over the Silverlight Application.    When I maximize the brows ...

Error encountered: Unexpected token while trying to implement React + Node.js tutorial on a blog platform

I recently started following a tutorial on Site Point in an attempt to create my own React app. However, I hit a roadblock at these specific steps: mkdir public npm install npm run developement The first command failed for me because I already had a &a ...

Ways to dynamically update CSS properties (such as changing the color scheme throughout the entire application)

I have a question... If you're interested in conditional styling, the best approach is to utilize either ng-class or ng-style. However... For instance, let's say I'm an admin and I would like to customize the color of my application using ...

Creating a dynamic side navigation menu that adjusts to different screen sizes

I have been working on a project's webpage that was initially created by another Software Engineer. After he left, I continued to work on the webpage. The issue I encountered is that he preferred a side menu over a navbar using the left-panel and righ ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Tips for adding animation to the div instead of the content

I have implemented a hover animation to animate the div, but unfortunately, when I added the animation to #i :hover {}, it ended up animating the words only. Moreover, the cursor transforms into a pointer solely when hovering over the words instead of the ...

Confirming the existence of a folder with AngularJS

Currently, I am attempting to determine if a folder exists so that I can make decisions on which files to include using ng-include. This is what I have so far: $scope.isVisible = { buttons: checkForClientOverwride('buttons'), it ...

Package for running scripts in Node Package Manager

Currently, I am working on developing an npm package that will automatically insert a specific npm script into any package.json file that it is being used. Unfortunately, after going through the npm package.json/script documentation, I haven't been ab ...

jqGrid: Enhance the advanced search dialog by updating the column dropdown feature following the addition of a column using the column

I am encountering an issue with the advanced search feature of the jqGrid. It appears that the advanced search dialog box is only generated once, when the searchGrid function is called. After I have opened the advanced search dialog once and then add a co ...

Make sure that the function displays the output once it has been received using the jQuery.get method

This script fetches data using the $.get method from an XML file on an ASP ashx server: $.get("http://www.example.com/example.ashx", { From: txtFrom, To: txtTo, Date: txtTime }, function (data) { var arr ...

What is the technique for integrating a required file into an Angular module using Browserify?

My Angular SPA build is set up to use NPM for calling the browserify script to bundle it. To execute the build process from the terminal, you can run npm run build:js, which triggers the following script in the package.json file: "build:js": "browserify - ...

Maintaining a reliable and efficient way to update the userlist in a chatroom using PHP, AJAX, and SQL

I've successfully created a chatroom using PHP, JavaScript, AJAX, and SQL without the use of JQuery or any other tools. I maintain user persistence through session variables to keep users visible on the front page of my website (www.chatbae.com). How ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

Transferring Data to EJS Template

I have been facing a challenge in passing a value from a POST route to an EJS file for display. Despite trying various methods like redirecting, sending, and rendering the results, the data won't make its way to the EJS file. Below is the POST route ...