问题
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?
回答1:
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>
回答2:
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>');
来源:https://stackoverflow.com/questions/31710021/jquery-replacewith-html-element-to-div-class