views:

1302

answers:

2

Of course, there are a whole range of possible errors relating to document validity, but my immediate stumbling block occurs when changing a paragraph (p) into an address element. My current method is (more-or-less):

var p = $('p#test');
p.replaceWith('<address>' + p.html() + '</address>');

but that fails for this specific case; it works perfectly for p -> blockquote or h2 -> h3. Firebug suggests that a self-closing element (<address/>) has been added to the document, for some reason.

Can anyone spot the bug or suggest an alternative method?

A: 

You'll could use a placeholder around the title:

<span id="demo"><h1>Title</h1></span>

Then use JavaScript DOM to create new values for the innerHTML property.

<script type="javascript">

setTitle = function(id, tag, title) {
  var container = document.getElementById(id);
  container.innerHTML = '<' + tag + '>' + title + '</' + tag + '>';
}

setTitle('demo', 'h1', 'My Title');

</script>
Ady
Why has this been downvoted? It's unhelpful to downvote something like this without explaining why...
Ben
+8  A: 
var p = $('p#test');
var a = $('<address></address>').
    append(p.contents());
p.replaceWith(a);

Your solution is subject to all sorts of horrible HTML escaping issues and possibly injection attacks.

Daniel Cassidy
Daniel, thanks for the answer, but doesn't that assume that an address element already exists? Imagine the body consists solely of "<p>stuff</p>" and I want it to be "<address>stuff</address>"
Bobby Jack
No, the syntax $('<address></address>') creates a new address element which can then be used to replace the p.However do notice that I've just made a correction to my original post.
Daniel Cassidy
Wow - that's a new bit of jQuery on me :) Thanks, Daniel - works like a dream.
Bobby Jack