innerHTML and outerHTML to Get and Replace HTML content Get and Replace HTML content with innerHTML
innerHTML is a JavaScript property that can be used to get the HTML content added into a HTML element in web page, and also it can be used to replace the content into a HTML element with other content.. 1. Syntax, get content with innerHTML var content = element.innerHTML; ! "xample
<div id="id1">JavaScript <p>Example innerHTML - http://co r!e!"e#$net/%ava!cript/</p> </div> <!cript> var cnt = doc ment$&etElement'()d*+id1+,$innerHTMLalert*cnt,/. /e! lt: JavaScript <p>Example innerHTML - http://co r!e!"e#$net/%ava!cript/</p> ./ </!cript>
#. Syntax, add $replace content with innerHTML element.innerHTML = 'HTML content'; ! "xample
<div id="id1">JavaScript</div> <!cript> doc ment$&etElement'()d*+id1+,$innerHTML = +<p>Example innerHTML http://co r!e!"e#$net/%ava!cript/</p>+/. /e! lt: <div id="id1"><p>Example innerHTML - http://co r!e!"e#$net/%ava!cript/</p></div> ./ </!cript>
Get and Replace HTML content with outerHTML
outerHTML is a JavaScript property that can be used to get the string with a HTML element, including its tag, attributes and child elements, also it can replace a HTML tag %including its content& with other HTML content. 1. Syntax, get HTML content with outerHTML var content = element.outerHTML; ' The di((erence between innerHTML and outerHTML is that the innerHTML gets the content added into a HTML element, but the outerHTML gets also the tag and attributes representing that element. ! "xample
<div id="id0">JavaScript <p>Example o terHTML - 1o r!e!2e#$net/%ava!cript/</p> </div> <!cript> var cnt = doc ment$&etElement'()d*+id0+,$o terHTMLalert*cnt,/. /e! lt: <div id="id0">JavaScript <p>Example o terHTML - 1o r!e!2e#$net/%ava!cript/</p> </div> ./ </!cript>
#. Syntax, add $replace content with outerHTML element.outerHTML = 'HTML content'; ' The di((erence between innerHTML and outerHTML is that outerHTML replace the element itsel( with the new content. ! "xample
<div id="id1"> <div id="id0">JavaScript</div> </div> <!cript> doc ment$&etElement'()d*+id0+,$o terHTML = +<p>Example o terHTML 1o r!e!2e#$net/%ava!cript/</p>+/. /e! lt: <div id="id1"> <p>Example o terHTML - 1o r!e!2e#$net/%ava!cript/</p> </div> ./ </!cript>