Rawand
Rawand

Reputation: 443

How can I get the HTML for an element with JavaScript?

I want to get the exact HTML of the element I want

like if I have this:

<div class="input">
  <input type="number" id="nanometer" autocomplete="off" class="field" placeholder="nm" oninput="exchange()">
</div>

I want to get that exact HTML code in my JavaScript:

var nano = document.getElementById("nano")

and now I expect nano to be:

<input type="number" id="nano" autocomplete="off" class="field" placeholder="nm" oninput="exchange()">

and for my work, I have to make it duplicate itself like this:

<input type="number" id="nano" autocomplete="off" class="field" placeholder="nm" oninput="exchange()">
<input type="number" id="nano" autocomplete="off" class="field" placeholder="nm" oninput="exchange()">

by this code:

document.getElementById(nano).outerHTML += nano

but it wont work

Upvotes: 0

Views: 101

Answers (2)

Peter B
Peter B

Reputation: 24147

Although the question is for making a clone using HTML strings, it is better to not work with HTML strings but with DOM elements instead. Those are the objects that a browser uses internally.

Using DOM elements it is much easier to control the results, esp. if you need to make changes to the new item - such as giving it a new id, which is mandatory because every id on every page should be unique.

Here is an example:

var nano = document.getElementById("nano");
var parent = nano.parentNode;

var clone = nano.cloneNode(true);
clone.id = "newNano";
clone.setAttribute("value", 123);

parent.insertBefore(clone, nano.nextSibling);
<input type="number" id="nano" autocomplete="off" class="field" placeholder="nm" oninput="exchange()">

Upvotes: 1

First, get the outer HTML. Then, to duplicate it, you have to append the new HTML to the parent node of whatever you're trying to get. Also, you would need to replace the new ID with something unique. So it would be:

    var nano = document.getElementById("nano"),
        outer = nano.outerHTML,
        newOuter = outer.replace(
          'id="',
          'id="' + Date.now()
        ),
        parent = nano.parentNode;
    
    parent.innerHTML += newOuter;
    console.log(parent.innerHTML)
<div>
<input type="number" id="nano" autocomplete="off" class="field" placeholder="nm" oninput="exchange()">
</div>

Upvotes: 0

Related Questions