Skip to content Skip to sidebar Skip to footer

How Do I Change An Element (e.g. H1 -> H2) Using Jquery / Plain Old Javascript?

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.

Solution 1:

var p = $('p#test');
var a = $('<address>').
    append(p.contents());
p.replaceWith(a);

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

Solution 2:

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>

Post a Comment for "How Do I Change An Element (e.g. H1 -> H2) Using Jquery / Plain Old Javascript?"