link1 link1and using the following $('.selected')....">

Get custom HTML with jQuery

<div> <a href="#" class="selected">link1</a> <a href="#">link1</a> </div> 

and using the following

$('.selected').html() I get

link1

as the return value.

How can I get the full html code of the selected DOM element, in this example, to get

<a href="#" class="selected">link1</a>

instead

thanks

+6
source share
5 answers

JQuery object:

 $('.selected') 

go to the DOM object:

 $('.selected')[0] 

UPDATE

 var str = $("<div />").append($('.selected').clone()).html(); console.log(str); 
+10
source

I know this works in Chrome, I don’t know about the rest:

 $("#yourElement")[0].outerHTML 

This property is from javascript (not jQuery) and gives you what you are looking for.

+12
source

I made a decision similar to the above, but without cloning.

 var test = $('#test').wrap('<div class="wrap-unwrap"></div>'); var str = test.parent().html(); test.unwrap(); console.log(str); 
+4
source

Just using the outerHTML property may not work in all browsers. You will need to serialize it yourself for browsers without outerHTML support. See this post for an explanation: How do I make OuterHTML in firefox?

0
source

You can try this jQuery plugin: http://darlesson.com/jquery/outerhtml/

-2
source

Source: https://habr.com/ru/post/904541/


All Articles