Steve Teale
Steve Teale

Reputation: 219

jQuery gets wrong html() for span after a p tag

<html>
<head>
<script 
    src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" 
    type="text/javascript"/></script>
<script>
$(function() {
    alert($('#s1').html());
});
</script>
</head>
<body>
<p/>
<span id="s1"><h3>Eggs</h3>One dozen please</span>
</body>
</html>

This page puts up a blank alert with the <p> tag, but with <br> it shows '<h3>Eggs</h3>One dozen please', as I'd expected.

This appears to be the case with Firefox 12.0 and Chrome 19.0. IE8 gets it right. Any ideas what might be happening?

Upvotes: 4

Views: 190

Answers (3)

Moin Zaman
Moin Zaman

Reputation: 25445

@pimvdb is right about closing the <p>

However, one other thing to note is that you have a <h3> which is a block element inside a <span> which is an inline element which is incorrect. inline elements should not contain blocks. Blocks can contain blocks and / or inlines.

For your eg. if you change the <span> to a <div> it works.

Upvotes: 2

Ricardo Binns
Ricardo Binns

Reputation: 3246

try this:

<p></p>

$(function() {
   alert($('#s1').html());
});

and will work. You need to close the tag <p></p>

Demo

Upvotes: 1

pimvdb
pimvdb

Reputation: 154828

The / has no meaning, at least not in HTML5. So you actually have:

<p>
  <span id="s1"><h3>Eggs</h3>One dozen please</span>

Since a <p> cannot contain an <h3>, the browser tries to make at least some sense out of it by interpreting it as:

<p>
  <span id="s1"></span>
</p>
<h3>Eggs</h3>One dozen please

Upvotes: 8

Related Questions