Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Self-closing div

Tags:

html

jquery

dom

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.

like image 958
ldp Avatar asked Oct 02 '22 08:10

ldp


1 Answers

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>
like image 148
TimWolla Avatar answered Oct 13 '22 10:10

TimWolla