4

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;" > 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 .

Jafar tm
  • 247
  • 2
  • 11

1 Answers1

2

You can get it from outerHTML property of DOM element object. Where you can get DOM element from jQuery object 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>


UPDATE 2 : Although you can get the calculated with property using 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>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188