JQuery .replaceWith() html element to div class

非 Y 不嫁゛ 提交于 2021-01-28 08:07:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!