Chris Phi
Chris Phi

Reputation: 11

JQuery .replaceWith() html element to div class

I want to replace

<div class="blog">Blog</h1>

with

<h1>Blog</h1>

which is inside a class name "sidebar"

I used this code but didn't work:

$(window).load(function() {
    $( ".sidebar h1" ).replaceWith( "<div class="blog">Blog</h1>" );
}

What is wrong on my code?

Upvotes: 1

Views: 1481

Answers (2)

SteJ
SteJ

Reputation: 1531

Firstly, your opening a div tag and closing an h1 tag.

Secondly, your quotes are mismatched within the .replaceWith bit.

I would do this instead:

<h1 id="replaceme">Blog</h1>
<script>
$(window).load(function() {
    $("#replaceme").replaceWith('<div class="blog">Blog</div>');

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

If you want double quotes within a string that is delimited by double quotes, you must escape them with a backslash:

"<div class=\"blog\">Blog</h1>"

Many programmers use single quotes for JavaScript strings, which makes it easier to use double quotes for embedded HTML.

Also note that tags should be closed with matching tags. Instead of

'<div class="blog">Blog</h1>'

… do this:

'<div class="blog">Blog</div>'

Here's a solution:

$('.sidebar h1').replaceWith('<div class="blog">Blog</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <h1>Blog</h1>
</div>

Upvotes: 1

Related Questions