13

Is there an issue with replacing the contents of a <span in jQuery.

I have this;

<span class='DimensionList'>
  some html
</span>

and

$('.DimensionList').html("<b>This is the new html</b>");

What I'm finding is that in FF the contents of the span are being added to. So the new HTML sits above the old.

In IE6, yes I have to cater for it, it's doing much the same.

EDIT

I have edited the question to show that there is html in the replacement html

3
  • api.jquery.com/html/#html2 "When we use .html() to set elements' contents, any contents that were in those elements is completely replaced by the new contents." The docs are clear. What jQuery version are you using? Commented Nov 4, 2010 at 3:55
  • I am using jquery-1.4.2.min.js. And yeah I know this works if I use a Div but not when I change it to a span. For the record, I can't use a div in this instance Commented Nov 4, 2010 at 4:05
  • 1
    Works for me. Reproduceable test case please. I don't think what you think is happening, is happening. Commented Nov 4, 2010 at 4:34

4 Answers 4

22

Since there's no markup in your replacement text, use text() instead of html():

$('.DimensionList').text("This is the new html");
Sign up to request clarification or add additional context in comments.

3 Comments

Try clearing the span first, then setting the new html, like $('.DimList').empty().html("<b>hello</b>").
If that doesn't work, I'm guessing your html (new and possibly existing) is not valid.
Ah huh. interesting. The markup is existing from a governement department and these people are less than, shall we say, tech savy. Maybe I need to clean their code first.
4

if you needed to use .html() you could empty it first: $('.DimensionList').html("").html("<b>This is the new html</b>");

Comments

2

You've capitalized DimensionList in your javascript and it is lowercase in your HTML source. They need to be identical. In other words, it is case sensitive.

Comments

0

Have you tried .text() ? It is similar to .html()

From jQuery's Documentation:

Unlike the .html() method, .text() can be used in both XML and HTML documents

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as < for <).

http://api.jquery.com/text/

2 Comments

I have yeah but I need to insert html. Sorry that's not evident in the question.
Well, can you post your actual code? It may not be a jQuery bug, it might be your code...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.