Reputation: 311
How to get HTML code of element in JavaScript with current element tags?
For example
<body><div><div class="big"><p>sometext</p></div></div></body>
var x = document.getElementsByClassName('big')[0]
and now I want get HTML code of x :
'<div class="big"><p>sometext</p></div>'
not only:
'<p>sometext</p>' like innerHTML.
Is there simpler method than that?
var div = document.createElement("div");
div.id='_fooo'; var parent = x.parentNode;
parent.insertBefore(div, x);
div.appendChild(x);
document.getElementById('_fooo').innerHTML
Upvotes: 0
Views: 2894
Reputation: 514
First of all, your html block has an error. <input>
is an empty element, and it cannot have child elements. So,
<input type="submit" class="big"><p>sometext</p></input>
is not a valid HTML.
http://stackoverflow.com/questions/13629410/create-input-as-child-of-input
Anyway, the answer to your question is 'outerHTML' attribute.
Replacing your <input>
tag with <div>
<div type="submit" class="big"><p>sometext</p></div>
var x = document.getElementsByClassName('big')[0];
var output = x.outerHTML // returns '<div type="submit" class="big"><p>sometext</p></div>'
Upvotes: 1
Reputation: 633
Get the parent of your current element and call get innerHTML on that, but that will give you all the children, so you might want to create a parent div for your element just so you can read it's content.
example
var x = document.getElementsByClassName('big')[0].parentElement.innerHTML
here your parent will be the body based on the given example, and it will get the next inside it which is what you want.
Upvotes: 0