Converting DOM elements back into HTML

domparser
convert string to html
convert html string to html javascript
convert string to html typescript
html to dom converter online
convert text to html javascript
convert html string to dom element react
dom parser

I am creating a script to rearrange <div> elements on a page. It can get them into an array, but that array's contents look like:

[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],

None of the following have worked:

my_array.innerHTML

my_array.outerHTML

my_array.html

my_array.toString()

So how can I get this array back into something that looks like: <div class="rect red"></div><div class="rect green"></div><div class="rect blue"></div><div class="rect yellow"></div>, and have that render as divs on the page?

Here is the full code:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.rect {width:24px; height:12px; border-radius:12px; border:4px solid rgba(0,0,0,0.25); margin-bottom:12px}
.red {background-color:#c21}
.green {background-color:#1c3}
.blue {background-color:#28f}
.yellow {background-color:#ed1}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
	<div class="rect red"></div>
	<div class="rect green"></div>
	<div class="rect blue"></div>
	<div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx){ //move the element one place earlier in the array
	var move = arr[ndx];
	arr.splice(ndx, 1); //from index #'ndx', remove 1 element
	arr.splice(ndx-1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}

$(".rect").click( function() { // rearrange the order of divs when one is clicked
	var sort = Array.from( $(this).parent().children() );
	var current_index = $(this).index();

	move_before(sort, current_index); // put each element into a new array
	var i = 0;
	var updated_arr = [];
	while (i <= sort.length) {
		updated_arr.push(sort[i]);
		i = i+1;
	}
	document.getElementById("target").innerHTML = updated_arr;
});
</script>
</body>
</html>

Use appendChild():

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.rect {width:24px; height:12px; border-radius:12px; border:4px solid rgba(0,0,0,0.25); margin-bottom:12px}
.red {background-color:#c21}
.green {background-color:#1c3}
.blue {background-color:#28f}
.yellow {background-color:#ed1}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
	<div class="rect red"></div>
	<div class="rect green"></div>
	<div class="rect blue"></div>
	<div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx){ //move the element one place earlier in the array
	var move = arr[ndx];
	arr.splice(ndx, 1); //from index #'ndx', remove 1 element
	arr.splice(ndx-1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}

$(".rect").click( function() { // rearrange the order of divs when one is clicked
	var sort = Array.from( $(this).parent().children() );
	var current_index = $(this).index();

	move_before(sort, current_index); // put each element into a new array
	var i = 0;
	var updated_arr = [];
	while (i <= sort.length) {
		updated_arr.push(sort[i]);
		i = i+1;
	}
  for(i=0;i<updated_arr.length-1;i++){
	document.getElementById("target").appendChild(updated_arr[i]);
   }
});
</script>
</body>
</html>

Converting HTML string into DOM elements?, Document element to serve as the context in which the HTML fragment will be parseHTML uses native methods to convert the string to a set of DOM nodes,� HTML DOM DOM Attributes. getNamedItem() JS Conversion. An HTMLCollection object is an array-like list of HTML elements.

Two minor changes to make it work:

  1. use < instead of =< in the loop to avoid one extra iteration.
  2. Use Element.appendChild() to add elements in a Node. You can read more about it here https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

Great job on using this!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      .rect {
        width: 24px;
        height: 12px;
        border-radius: 12px;
        border: 4px solid rgba(0, 0, 0, 0.25);
        margin-bottom: 12px;
      }
      .red {
        background-color: #c21;
      }
      .green {
        background-color: #1c3;
      }
      .blue {
        background-color: #28f;
      }
      .yellow {
        background-color: #ed1;
      }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  </head>
  <body>
    <div id="target">
      <div class="rect red"></div>
      <div class="rect green"></div>
      <div class="rect blue"></div>
      <div class="rect yellow"></div>
    </div>
    <script>
      function move_before(arr, ndx) {
        //move the element one place earlier in the array
        var move = arr[ndx];
        arr.splice(ndx, 1); //from index #'ndx', remove 1 element
        arr.splice(ndx - 1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
      }

      $(".rect").click(function() {
        // rearrange the order of divs when one is clicked
        var sort = Array.from(
          $(this)
            .parent()
            .children()
        );
        var current_index = $(this).index();

        move_before(sort, current_index); // put each element into a new array
        var i = 0;
        var updated_arr = [];
        while (i <= sort.length) {
          updated_arr.push(sort[i]);
          i = i + 1;
        }
        updated_arr.map(element =>
          document.getElementById("target").appendChild(element)
        );
      });
    </script>
  </body>
</html>

jQuery.parseHTML(), Today there's a little known (but standard) way for converting string to DOM with JavaScript: in the past, but that post illustrated element creation via document. To create DOM nodes from a string of HTML we'll use document. How do I get the HTML back out (for example, what if the html that went in� In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element. Properties and Methods The following properties and methods can be used on all HTML elements:

No need to create the updated_arr. Just join the outerHTML of the HTMLElement objects in sort array.

move_before(sort, current_index); document.getElementById("target").innerHTML = sort.map(elem => elem.outerHTML).join('');

Also update your event binding to $("#target").bind('click', '.rect', function() { ...... });

Convert String to DOM Nodes, So next step is to convert that “HTML string” into proper DOM elements to be able to traverse through the nodes and do your thing. Using jQuery� In JavaScript, there are a couple of ways one can use to convert HTML to DOM elements. DOMParser; document.createElement; DOMParser. DOMParser can parse XML or HTML source stored in a string into a DOM Document. After the conversion, the normal JavaScript call of handling DOM elements can be used, like getting element by id or using selectors.

JavaScript DOMParser, a good choice to convert HTML strings to , back() forward() go() length In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, The following properties and methods can be used on all HTML elements: toString(), Converts an element to a string � Convert HTML string to DOM element / Checkout Revealing the magic: How to properly convert HTML string to a DOM element article. I'm working on a chrome extension which accepts user text, work with it and output the result in a div. I used jQuery in the beginning, for several tasks, but later I decided to remove it and deal with pure javascript/DOM manipulations. The output div was filled by

HTML DOM Element Objects, Now let's create the same div with JavaScript (assuming that the styles are in the HTML/CSS already). Creating an element. To create DOM� The document.createRange().createContextualFragment function is an awesome, sane method for converting strings to DOM nodes within JavaScript. Ditch your old shims and switch to this performant, simple API! The Original Post: DOMParser. Today we have a standard way for converting string to DOM with JavaScript: DOMParser. The JavaScript

Modifying the document, To insert the HTML into the document rather than replace the A DOMString containing the HTML serialization of the element's descendants. with the HTML entity "<" , thereby essentially converting the HTML into raw text. I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild(). Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript.

Comments
  • Probably this: stackoverflow.com/questions/4239587/…
  • You have to call outerHTML on the array elements, not the array.
  • @Barmar Thanks. When I try my_array[i].html or similar things (like outer and inner) I get TypeError: my_array[i] is undefined What am I doing wrong?
  • You need to post your code.
  • @Barmar Done. :-)