Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the innerHtml, including the tag, using jQuery?

Sorry, if the title is too obscure ;D.

Actually the problem is, lets say i am this code.

<span id="spanIDxx" style="blah-blah">
   <tag1>code here </tag2> sample text 
   <tag2>code here </tag2> html aass hhddll
   sample text
</span>

Now if i will use the code.

jQuery("#spanIDxx").html();

then it will return just the innerHTML excluding <span id="spanIDxx" style="blah-blah">
but i want something which can return the innerHTML including the specified element.

like image 776
Rakesh Juyal Avatar asked Feb 23 '10 15:02

Rakesh Juyal


People also ask

How do I get innerHTML with jQuery?

jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.

How do I get the innerHTML element?

Setting the innerHTML property of an element To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

How do I get the HTML inside a div using jQuery?

To load external HTML into a <div>, wrap your code inside the load() function. To load a page in div in jQuery, use the load() method.

Can innerHTML contain HTML tags?

HTML specifies that a <script> tag inserted with innerHTML should not execute. For that reason, it is recommended that instead of innerHTML you use: Element.


1 Answers

This will create a new div and append a clone of your element to that div. The new div never gets inserted into the DOM, so it doesn't affect your page.

var theResult = $('<div />').append($("#spanIDxx").clone()).html();

alert( theResult );

If you need to use this frequently, and don't want to bother with adding yet another plugin, just make it into a function:

function htmlInclusive(elem) { return $('<div />').append($(elem).clone()).html(); }

alert( htmlInclusive("#spanIDxx") );

Or extend jQuery yourself:

$.fn.htmlInclusive = function() { return $('<div />').append($(this).clone()).html(); }

alert( $("#spanIDxx").htmlInclusive() );
like image 88
user113716 Avatar answered Nov 07 '22 07:11

user113716