lilHar
lilHar

Reputation: 1866

Alter unappened element's html tag type with javascript

So I have an element created by another process, created in a method akin to

var their_element = document.createElement("div");
/* Lots of stuff is done to their_element */

And that object is being passed to me later. It has not been appended anywhere yet. The problem is, I need it to be different html tag type when it finally hits the html, such as:

<form></form>

How do i change it? The solutions I have found involve editing after it's appended, not before.

Edit: Also, learned nodeName can't be assigned for this.

their_element.nodeName = "FORM"

doesn't work.

Also, this doesn't work either:

their_element.tagName = "FORM"

Also this didn't work either:

var outside = their_element.outerHTML;
outside = outside.replace(/div/g, 'form');
their_element.outerHTML = outside;

All of these still leave it as a DIV when appended. (And I'm not looking for jQuery)

Upvotes: 1

Views: 53

Answers (1)

wlh
wlh

Reputation: 3515

Check on this for cross-browser compatability, but there are properties and methods on elements that could be of use. Particularly, Element.attributes, Element.hasAttributes(), and Element.setAttribute(). See: https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes

I'm not going to use ES6 here, so we don't have to worry about transpiling. You can update if you want:

var el = document.createElement('div');
    el.id="random";
    el.style.background="red";
    el.style.width="200px";
    el.style.padding="10px";
    el.style.margin="10px";
    el.innerHTML="<input type='submit' value='submit'>";

console.log({"Element 1": el});

var newEl = document.createElement('form');

console.log({"Element 2 Before Transformation": newEl})

if (el.hasAttributes()) {
    var attr = el.attributes
    for (var i = 0; i < attr.length; i++) {
        var name = attr[i].name, val = attr[i].value;
        newEl.setAttribute(name, val)
    }
}

if (el.innerHTML) { newEl.innerHTML = el.innerHTML }

console.log({"Element 2 After Transformation": newEl})

document.body.append(el);
document.body.append(newEl); 

There are certain properties you need to account for like innerHTML, innerText, and textContent that would overwrite one another if multiples are set. You may also have to account for childNodes and what not.

Upvotes: 1

Related Questions