JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Block1</h2>
<p><strong>Title1</strong></p>
<p>contentち</p>
<!-- the amount of p with content may vary -->
<p>contentこ</p>
<p>contentそ</p>
<!-- the amount of p with highlighted title may vary -->
<p><strong>Title_N</strong></p>
<p>content</p>
<p>content</p>
<!-- the amount of h2 blocks may vary -->
<h2>Block_N</h2>
<p><strong>Other_Title</strong></p>
<p>content</p>
<hr/>
<em>OUTPUT</em>
<pre id="output"></pre>
JavaScript
const dom = document.body;
const results = [];
let currentBlock = {};
let currentContent = {};
let currentTitleContent = {};
console.log(dom)
Array.prototype.slice.call(dom.children).forEach((node) => {
if (node instanceof HTMLHeadingElement) {
if (Object.keys(currentBlock).length !== 0) {
currentContent[`TitleContent${(currentBlock.length || 0)/ 2 + 1}`] = currentTitleContent;
if (currentBlock.BlockContent)
currentBlock.BlockContent.push(currentContent);
else
currentBlock.BlockContent = [currentContent];
currentContent = {};
currentTitleContent = {};
results.push(currentBlock);
currentBlock = {};
}
currentBlock.BlockName = node.textContent;
currentBlock.BlockContent = []
} else if (node instanceof HTMLParagraphElement) {
if (node.children[0] instanceof HTMLElement) {
if (Object.keys(currentContent).length !== 0) {
currentContent[`TitleContent${(currentContent.length || 0) / 2 + 1}`] = currentTitleContent;
currentBlock.BlockContent.push(currentContent);
currentContent = {};
currentTitleContent = {};
}
currentContent[`TitleName${(currentContent.length || 0) / 2 + 1}`] = node.textContent;
} else {
currentTitleContent[`Content${(Object.keys(currentTitleContent || {}).length || 0) + 1}`] = node.textContent;
}
}
});
currentContent[`TitleContent${(currentContent.length || 0) / 2 + 1}`] = currentTitleContent;
currentBlock.BlockContent.push(currentContent);
results.push(currentBlock);
document.getElementById('output').innerText = JSON.stringify(results, null, 2);