0

I have an Html string like this:

<div id="foo">
    <h1 class="greeting">Hello World!</h1>
</div>

I need to convert this html string to Object in Javascript. i.e., I should get the same object result when used .children() method in jquery.I tried something like this:

a = '<div id="foo">
    <h1 class="greeting">Hello World!</h1>
</div>';
eval("{"+a+"}");
console.log(a);

But it didn't work. What method should I use in javascript to convert HTML string to Object notation. I should get each children node in object form. I do not want to use Jquery in this solution. I am expecting the exact output as shown in console

enter image description here

9
  • @A4L Your link does not have the answer what I expected. That page has irrelevant answers Commented Apr 15, 2014 at 13:11
  • 1
    That link is the answer. You have an HTML string that you need converted to a DOM structure. You do not have JSON. Commented Apr 15, 2014 at 13:12
  • What do you want achieve? Commented Apr 15, 2014 at 13:13
  • I need HTML string to Object for further process Commented Apr 15, 2014 at 13:14
  • @A4L I am expecting the output as shown in question Commented Apr 15, 2014 at 13:19

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I need to achieve the same result using Javascript. I don't want to use any jquery library
@Ganesh but in image it is a jQuery object
I knew that. I need to get the same object using Javascript. What method should I use instead of .children() to achieve this result.
+1 Nice and simple. Here I though OP wanted an elaborate wrapper for all that like jQuery without using jQuery. Well done.
1

Edited

var a = '<div id="test"></div>';

var htmlObject = document.createElement('div');

htmlObject.innerHTML = a;

htmlObject.getElementById("test") = data;

Comments

0

Do you want like this

<script>
var htmlStrObj = {};
htmlStrObj.container = '<div id="foo"><h1 class="greeting">Hello World!</h1></div>';
console.log(htmlStrObj);
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.