Victoria
Victoria

Reputation: 911

jQuery [object Object] error when trying to convert first h2 tag to an h1

I'm working with a webpage where all the headings use h2 tags. I'd like to convert the first heading so that it uses an h1.

This is the code I'm using:

<script type="text/javascript">
var myHeader = $('h2:first');
var myHeaderHTML = myHeader.html();

alert("myHeader: " + myHeader);
alert("myHeaderHTML: " + myHeaderHTML);

$(document).ready(function() {
$(myHeader).replaceWith("<h1>" + $(myHeaderHTML) + "</h1>");
});
</script>

However, when I reload the page I get an [object Object] error wrapped within h1 tags. As you can see above, I put a couple of alerts into the code so I can see what values the variables contain, and it's the myHeader variable which contains [object Object]. The myHeaderHTML variable contains what I expect.

How can I fix this?

Upvotes: 0

Views: 202

Answers (4)

loganfsmyth
loganfsmyth

Reputation: 161597

Here's a potentially safer way to do this that doesn't require putting the HTML contents out into a string:

<script type="text/javascript">
  $(function(){
    $('h2:first').wrapInner('<h1>').find('h1').unwrap();
  });
</script>

Upvotes: 0

Bergi
Bergi

Reputation: 665080

By $(myHeaderHTML) you're wrapping the HTML string in a jQuery object, which will be serialized [object Object] when concatenated with other strings ("<h1>").

Use

$(document).ready(function() {

    var myHeader = $('h2:first');
    var myHeaderHTML = myHeader.html();

    alert("myHeader: " + myHeader); // alerts [object Object] as well
    alert("myHeaderHTML: " + myHeaderHTML);

    myHeader.replaceWith("<h1>" + myHeaderHTML + "</h1>");
});

Upvotes: 1

user229044
user229044

Reputation: 239432

This is wrong:

"<h1>" + $(myHeaderHTML) + "</h1>"

You're adding a string to an object, which converts the object to the string "[Object object]" and performs concatenation.

It should be:

 "<h1>" + myHeaderHTML + "</h1>"

Upvotes: 4

Daniel A. White
Daniel A. White

Reputation: 190986

You shouldn't need to call jquery again.

$(myHeader).replaceWith("<h1>" + myHeaderHTML + "</h1>");

Upvotes: 2

Related Questions