0

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
1
  • outerHTML, though input is an empty element and can't have HTML or any other content. Commented Mar 16, 2015 at 15:21

2 Answers 2

1

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

1 Comment

An element being an inline element doesn't mean it couldn't have content, most of the inline elements can have content. An empty element (previously known as void element) would be a correct term.
0

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.

2 Comments

I know this method, but what if i have more childrens? Is There not simpler method than that? var div = document.createElement("div"); div.id='_fooo'; var parent = this.parentNode; parent.insertBefore(div, this); div.appendChild(this); document.getElementById('_fooo').innerHTML
try the outerhtml idea on the input element, that might give you exactly what you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.