0

I have a html code like this:

<div id="sample" style="height: 100px">
     <div class="test">
       ...
     </div>
     <div class="test">
       ...
     </div>
     <div class="test">
       ...
     </div>
     ...
 </div>

I need to get <div id="sample" style="height: 100px"> string from this DOM. How can I do this?

hamed
  • 7,939
  • 15
  • 60
  • 114

3 Answers3

1

Assuming you want to get the div's HTML as a string without the children in that string, an approach could be to select the element, clone it (to avoid messing with the DOM), wrap the clone in another element, crawl up to that element and take that elements contents.

    var str = $("#sample").clone().empty().wrap("<div/>").parent().html();

Here's a jsfiddle-demo. So to clarify:

.clone() yields:

<div id="sample" style="height: 100px">
 <div class="test">
   ...
 </div>
 <div class="test">
   ...
 </div>
 <div class="test">
   ...
 </div>
 ...
</div>

.empty()

<div id="sample" style="height: 100px"></div>

Side note: From here, instead of using .wrap().parent().html(), you could fetch the original DOM-element and access the outerHTML-attribute (i.e. $("#sample").clone().empty()[0].outerHTML). However, the first-mentioned approach defies cross-browser compatibility issues.

.wrap("<div/>")

<div><div id="sample" style="height: 100px"></div></div>

.parent() refers to the newly created outer div, and .html() returns the content of that, which will leave you with the string <div id="sample" style="height: 100px"></div>

rdiz
  • 6,136
  • 1
  • 29
  • 41
0

Try this

var str = $('#sample')[0].outerHTML.split('\n')[0];

alert(str);

http://jsfiddle.net/d27frp8a/

Ivan Sivak
  • 7,178
  • 3
  • 36
  • 42
0

Just another way:

var element = $('#sample')[0];
var outer = element.outerHTML;
var inner = element.innerHTML;
var line = outer.substring(0, outer.indexOf(element.innerHTML));
  1. Get the string representation of full element
  2. Get the string representation of the content inside
  3. Get a substring from the beginning to a shift of inner part
SerG
  • 1,251
  • 4
  • 18
  • 37