Hi i have the following html code
<div id="im" style="width:20px; color:red;" >12</div>
i need to get this html structure <div id="im" style="width:20px; color:red;" >
<div id="im" style="width:20px; color:red;" >
to a variable . How i get this ?
To get the text , or content inside the div we can use
$( "#im" ).html();
But i want to get the htm structure , not the content . Please help.
Edit
i understand that we can use $( "#im" ).prop('outerHTML');
From this result how can i get the width
?
i know we can use .css("width"), but i need to get this from prop('outerHTML')
.
Please help .
You can get it from outerHTML
property of DOM element object. Where you can get DOM element from jQuery objec t using the index.
$("#im")[0].outerHTML
UPDATE 1 : To get the width from attribute use attr()
method to get attribute value and String#match
method to get the style property value using regex from the string.
console.log( $('#im').attr('style').match(/width\\s?:([^;]+)/)[1] )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="im" style="width:20px; color:red;">12</div>
css()
method.
console.log( $('#im').css('width') )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="im" style="width:20px; color:red;">12</div>
UPDATE 3 : To get it from the string wrap it with jQuery and do the same.
console.log( $($('#im')[0].outerHTML).css('width') ) // or console.log( $($('#im')[0].outerHTML).attr('style').match(/width\\s?:([^;]+)/)[1] )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="im" style="width:20px; color:red;">12</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.