In image it is a jQuery object which you can create using following code

var a = '<div id="foo">\
    <h1 class="greeting">Hello World!</h1>\
</div>';
var aDom = jQuery(a);
console.log(aDom );

Pure JavaScript: jsfiddle

var e = document.createElement("div");
e.id = "foo";
e.innerHTML = '<h1 class="greeting">Hello World!</h1>';

console.log(e);
Answer from Anoop on Stack Overflow
🌐
npm
npmjs.com › package › html-to-object
html-to-object - npm
July 27, 2017 - A lightweight HTML parser for JavaScript that converts your native HTML code into an Array of JavaScript Objects. ... Returns the parsed elements as prebuilt DOM nodes to easily append them to the page.
      » npm install html-to-object
    
Published: Jul 27, 2017
Version: 1.3.7
Author: Max Sandelin
Discussions

convert HTML DOM element to JavaScript Object? - Stack Overflow
I have seen this post, but all I want to do is get the element, not do any parsing and build something new and ideally in dev tools. ... what does it mean javascript object? div equivalent javascript object, mean you are mixing HTML and Javascript. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Convert object to HTML element - Stack Overflow
JSON is a data format, and in JavaScript you can only have JSON in a string. See What is the difference between JSON and Object Literal Notation? ... Use addEventListener to register events on Element and .bind(thisArg) to have specified argument as this-context More on stackoverflow.com
🌐 stackoverflow.com
Initial Idea with Convert HTML Entities
Tell us what’s happening: Below I have my initial idea. It’s nothing much but I’m testing the waters to see if I’m on the right track. I feel skeptical about the transformation of str into an array. Also, I don’t know if it’s necessary/useful/feasible to “convert” an array into ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
12
0
February 2, 2019
converting a javascript string to a html object - Stack Overflow
can I convert a string to a html object? like: string s = ' '; var htmlObject = s.toHtmlObject; so that i can later on get it by id and do some changing in its sty... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Dustin John Pfister
dustinpfister.github.io › 2017 › 11 › 06 › nodejs-html-to-json
Converting html code to a JavaScript object in node.js with html-to-json | Dustin John Pfister at github pages
November 19, 2019 - As such I put together a simple example to just test out how it works, by seeing if I can just pull the text from a single paragraph element just for starters. So with that said there is the parse method of this project where the first argument that is given is an html string, and the second argument given is an object the serves as a filter.
🌐
PixelsTech
pixelstech.net › home › articles › convert html to dom elements using javascript
Convert HTML to DOM elements using JavaScript | PixelsTech
August 19, 2017 - Another way of converting HTML to DOM is to use the traditional document.createElement method. After creating the element, the HTML string can be assigned to the innerHTML attribute of the element and the JS engine would parse it to the child ...
🌐
GitHub
github.com › hamidyfine › html-to-object
GitHub - hamidyfine/html-to-object: A simple tool that allows you to convert HTML files into JavaScript objects and write them to a JSON file.
The convert-html-to-object CLI is a simple tool that allows you to convert HTML files into JavaScript objects and write them to a JSON file.
Author: hamidyfine
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › browser › form to object
How can I convert the data from an HTML form to a JavaScript object? - 30 seconds of code
January 21, 2024 - After getting a FormData object, we need only convert it to an object, using Object.fromEntries(). This results in a plain JavaScript object with the form field names as keys and their values as values.
Find elsewhere
🌐
Designcise
designcise.com › web › tutorial › how-to-convert-html-form-data-to-javascript-object
How to Convert HTML Form Data to JavaScript Object? - Designcise
February 22, 2023 - In JavaScript, you can convert HTML form values to an object in the following way: Use the FormData API to access form data; Store form data (as key/value pairs) in an object — if an element has multiple values, store an array of all the values.
🌐
GitHub
gist.github.com › emcode › 2688828
How to convert HTML form data to JS object (for using with AJAX) · GitHub
How to convert HTML form data to JS object (for using with AJAX) Raw · form-script.html · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Melvin George
melvingeorge.me › blog › convert-html-form-tag-input-values-to-object-javascript
How to easily convert HTML form tag input values to an object in JavaScript? | MELVIN GEORGE
May 6, 2021 - To convert the input values from an HTML form tag to an object, you can use the FormData() constructor available in the global window object in JavaScript.
🌐
freeCodeCamp
forum.freecodecamp.org › programming › javascript
Initial Idea with Convert HTML Entities - JavaScript - The freeCodeCamp Forum
February 2, 2019 - Tell us what’s happening: Below I have my initial idea. It’s nothing much but I’m testing the waters to see if I’m on the right track. I feel skeptical about the transformation of str into an array. Also, I don’t kno…
Top answer
1 of 1
1

I went for the recursive approach and created an output that is similar to your expected output.

const myHtml = `
  <span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: justify;">

  In nec <i>convallis</i> justo. Quisque egestas mollis nibh non hendrerit. <strong>Phasellus</strong> tempus sapien in ultricies aliquet. Maecenas nec risus viverra tortor rhoncus venenatis in sit amet enim. Integer id ipsum non leo finibus sagittis in eu velit. Curabitur sed dolor dui. <span>Mauris <strong>aliquam <i>magna</i></strong> a ipsum</span> tincidunt tempor vitae sit amet ante. Maecenas pellentesque augue vitae quam faucibus, vel convallis dolor placerat. Pellentesque semper justo a turpis euismod, ac gravida enim suscipit.</span>
  `;

let revisedHtml;

const parser = htmlStr => {
  let htmlElements = parse(htmlStr);
  revisedHtml = htmlElements.childNodes.map(node => {
    return createTranslatedNode(node);
  });
  return htmlElements;
};

const createTranslatedNode = node => {
  let currentNode = {};
  // This is a textNode.
  if (!node.rawTagName) {
    currentNode = { value: node?.rawText?.trim() };
  }
  // This is a tagNode
  if (node.rawTagName) {
    currentNode = {
      openTag: `<${node.rawTagName} ${node.rawAttrs}>`,
      closingTag: `</${node.rawTagName}>`
    };
  }

  if (node?.childNodes?.length === 1 && !node?.childNodes[0].rawTagName) {
    currentNode.value = node?.childNodes[0].rawText?.trim();
  }

  if (node?.childNodes?.length > 1) {
    currentNode.children = node.childNodes.map(childNode => {
      return createTranslatedNode(childNode);
    });
  }

  return currentNode;
};

console.log(revisedHtml);

I do some assumptions with the open and close tags since I just do some string concatination to add the <> around the tags. Other than that I trim() the value inputs to remove the unwanted whitespace around the value.

This does make some assumptions about the html, like it always having start and closing tags, and such. A further improvement that could be done would be to test for that also.

🌐
Wtools
wtools.io › html-to-javascript-converter
Online HTML to JavaScript Converter - wtools.io
Just paste your HTML code to the textarea above and click to the button "Convert" and you will get Javascript statements or variable in the next textarea.
🌐
Stack Overflow
stackoverflow.com › questions › 28546181 › converting-html-markup-to-object
javascript - converting html markup to object - Stack Overflow
I use the innerHTML property: var html = document.createElement("html"); html.innerHTML = "<body><h1>headline</h1><p>my content</p></body>"; nodeToJSON(html); ... Im getting an empty object if i pass <html><head><title>Hello!</title></head>...
Top answer
1 of 3
4

You can use recursion. And this seems a good case for a generator function. As it was not clear which tags should be retained in format (apparently, not p), I left this as a configuration to provide:

const formatTags = new Set(["b", "big", "code", "del", "em", "i", "pre", "s", "small", "strike", "strong", "sub", "sup", "u"]);

function* iterLeafNodes(nodes, format=[]) {
    for (let node of nodes) {
        if (node.nodeType == 3) {
            yield ({text: node.nodeValue, format: format.length ? [...format] : null});
        } else {
            const tag = node.tagName.toLowerCase();
            yield* iterLeafNodes(node.childNodes, 
                                 formatTags.has(tag) ? format.concat(tag) : format);
        }
    }
}

// Example input
const strHTML = "<p>Hello World</p><p>I am a text with <strong>bold</strong> word</p><p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>"
const nodes = new DOMParser().parseFromString(strHTML, 'text/html').body.childNodes;
let result = [...iterLeafNodes(nodes)];

console.log(result);

Note that this will still split the text when it is spread over multiple tags, which are considered non-formatting tags, like span.

Secondly, I'm not convinced that having null as a possible value for format is more useful then just an empty array [], but anyway, the above produces null in that case.

Special case - insertion of \n

In comments you ask for the insertion of a line break after each p element.

The code below will generate that extra element. Here I also used [] instead of null for format:

const formatTags = new Set(["b", "big", "code", "del", "em", "i", "pre", "s", "small", "strike", "strong", "sub", "sup", "u"]);

function* iterLeafNodes(nodes, format=[]) {
    for (let node of nodes) {
        if (node.nodeType == 3) {
            yield ({text: node.nodeValue, format: [...format]});
        } else {
            const tag = node.tagName.toLowerCase();
            yield* iterLeafNodes(node.childNodes, 
                                 formatTags.has(tag) ? format.concat(tag) : format);
            if (tag === "p") yield ({text: "\n", format: [...format]});
        }
    }
}

// Example input
const strHTML = "<p>Hello World</p><p>I am a text with <strong>bold</strong> word</p><p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>"
const nodes = new DOMParser().parseFromString(strHTML, 'text/html').body.childNodes;
let result = [...iterLeafNodes(nodes)];

console.log(result);

2 of 3
1

You can recursively loop over the child nodes and construct the desired array using an array like FORMAT_NODES.

const FORMAT_NODES = ["strong", "em"];

function getText(node, parents = [], res = []) {
  if (node.nodeName === "#text") {
    const text = node.textContent.trim();
    if (text) {
      const format = parents.filter((p) => FORMAT_NODES.includes(p));
      res.push({ text, format: format.length ? format : null });
    }
  } else {
    node.childNodes.forEach((node) =>
      getText(node, parents.concat(node.nodeName.toLowerCase()), res)
    );
  }
  return res;
}

const container = document.querySelector("#container");
const result = getText(container);
console.log(result);
<div id="container">
  <p>Hello World</p>
  <p>I am a text with <strong>bold</strong> word</p>
  <p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>
</div>

Relevant Documentations:

  • Node.childNodes
  • Node.parentNode
  • Array.prototype.concat
  • Array.prototype.includes
🌐
Quora
quora.com › What-is-the-process-for-converting-an-HTML-string-into-a-DOM-object-using-JavaScript
What is the process for converting an HTML string into a DOM object using JavaScript? - Quora
Answer: Assigning the HTML string directly to an Element.innerHTML is probably the easiest and the most optimal way of doing it as all the work is done by the browser. E.g. elem.innerHTML = ‘ this is hello world Once the above statement is executed, the HTML string will ...
🌐
Reddit
reddit.com › r/jquery › converting html table to js object stumped
r/jquery on Reddit: Converting HTML Table to JS Object Stumped
October 6, 2018 -

Hello,

I'm working on a horrible site that I can't control that presents relevant data I need to scrape in the form of a HTML table. As a version 1, I've collected the data I used with specific indexes. But seeing as that's more fragile than not, I would like to iterate upon this code I found.

Goal: Skip over blank table data cells and only collect table cells with data and be able to make a key:value pair with the table header cell if there is one.

Original Source:https://stackoverflow.com/questions/9927126/how-to-convert-the-following-table-to-json-with-javascript Source: http://jsfiddle.net/s4tyk/

var myRows = [];
var headersText = [];
var $headers = $("th");    

// Loop through grabbing everything    
var $rows = $("tbody tr").each(function(index) {    
$cells = $(this).find("td");    
myRows[index] = {};    

$cells.each(function(cellIndex) {    
// Set the header text    
if(headersText[cellIndex] === undefined) {    
  headersText[cellIndex] = $($headers[cellIndex]).text();    
}    
// Update the row object with the header/cell combo    
myRows[index][headersText[cellIndex]] = $(this).text();    
});   
});    

// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax 
request)    
var myObj = {    
"myrows": myRows    
};    
alert(JSON.stringify(myObj));    

The problem arises where I have a lot of empty table cells which then gives me some empty keys.

Example Table

whitespace Center align whitespace
This No Data This
column column No Data
will No Data will
be be No Data
left center right
No Data aligned aligned

I've been console logging everything, but I'm just not getting where I would do this in the code.

Top answer
1 of 2
2
I ended up just going through each table row traversing the structure of the table with jQuery and then filtering for the data I want. It's probably inbetween the solution I really want the one I came up with before. Version 2 Solution: jQuery('#table tbody tr td table').each(function(index) { var string1 = jQuery(this).text().split('delim').join('-'); var string2 = string1 + 'test works'; console.log( string2 ); }); When I have more time, I would like to work some more on the proposed solution above.
2 of 2
2
This should do what you are looking for: var headers = $('table thead th').toArray().map(th => $(th).text()) var validColumnIndexes = headers.reduce((out, header, i) => header ? out.concat([i]) : out, []) var rows = $('table tbody tr').toArray().reduce((out, tr) => { var cells = $(tr).find('td') var obj = {} var hasData = false validColumnIndexes.forEach(i => { var data = cells.eq(i).text() if (data) { obj[headers[i]] = data hasData = true } }) if (hasData) { out.push(obj) } return out }, []) The end result of your example table should look like: [ { "Center align": "column" }, { "Center align": "be" }, { "Center align": "center" }, { "Center align": "aligned" } ] It creates the row object using the column headers as keys, if the column header is not blank, and only populates the key on the object if there is text in the cell. And if there were no keys set on the object, meaning all valid columns did not contain data for this row, then the object is not added to the list.