5

I'm working against a legacy system which produce self-closing div when the div contains nothing.

I want use jQuery to get inner html of some div, but if the div is self-closing, jQuery always get wrong html.

See the demo code bellow:

<!doctype html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="application/javascript">
        $(function () {
            var s = $('.b').html();
            alert(s);
        });
    </script>
</head>
<body>
    <div class="a"></div>
    <div class="b" />
    <div class="c">This is c</div>
</html>

When I run this code, I get this result:

enter image description here

Please help me, any suggestions would be appreciated.

rene
  • 41,474
  • 78
  • 114
  • 152
ldp
  • 360
  • 2
  • 11
  • What's the doctype? If it's not an XHTML doctype, can you force it to use one? – tvanfosson Mar 11 '14 at 02:00
  • @tvanfosson: – ldp Mar 11 '14 at 09:48
  • Is there any way to change the doctype so that it matches the standard (XHTML) that the documents are being served with? I would think that the browser would obey the doctype if you set it to a type that matched the document structure. – tvanfosson Mar 11 '14 at 13:26

1 Answers1

5

I suspect this is not possible, as per Are self-closing tags valid in HTML5? elements ending in a slash are equivalent to ones that don't.

jQuery operates on the DOM the browser generates and the browser sees the element as open, see this example:

var s = $('.b').parent().html(); // <div class="a"></div><div class="b"><div class="c">This is c</div></div>
Community
  • 1
  • 1
TimWolla
  • 31,849
  • 8
  • 63
  • 96
  • Is this is a fault of JQuery? or how we can do to regard the DOM `
    ` as a blank one?
    – Jesse Mar 11 '14 at 02:10
  • @jesse No, this is not jQuery's fault, it is the browsers fault neither, it is the fault of the programmer of this legacy system. I don't think the issue can be easily circumvented either. – TimWolla Mar 11 '14 at 02:12
  • OK, thank you for your answer, I see, does it means that we should create a blank DOM like `
    ` instead of `
    ` when it is necessary?
    – Jesse Mar 11 '14 at 02:17
  • @jesse Yes. Only an explicit close works in HTML 5 (or everything except XHTML), unless the element is self closing (or **Void** as the W3C calls them) – TimWolla Mar 11 '14 at 02:19
  • 1
    @TimWolla: Lucky the legacy system's html has fixed format, and the second div rarely contains a div like the third div. So I solve my problem in this way: var s = $('.b').html().trim(); if(s.indexOf('
    ') == 0){ s = ''; }
    – ldp Mar 11 '14 at 10:00