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?