最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery replace <p> tag with line break - Stack Overflow

programmeradmin0浏览0评论

I have a html text like this:

<div>
    <p>1111</p>
    <p>2222</p>
    <p>3333</p>
</div>

I want to replace <p> tag with line break but make all text into <p> tag:

<div>
    <p>
        1111
        <br/>
        2222
        <br/>
        3333
        <br/>
    </p>
</div>

I have tried with replaceWith but the result was different from what I want

I have a html text like this:

<div>
    <p>1111</p>
    <p>2222</p>
    <p>3333</p>
</div>

I want to replace <p> tag with line break but make all text into <p> tag:

<div>
    <p>
        1111
        <br/>
        2222
        <br/>
        3333
        <br/>
    </p>
</div>

I have tried with replaceWith but the result was different from what I want

Share Improve this question asked Nov 28, 2015 at 9:31 AminesrineAminesrine 2,1406 gold badges36 silver badges65 bronze badges 1
  • try "\n" new line instead "<br/>" line break. – Kishor Pawar Commented Nov 28, 2015 at 9:40
Add a ment  | 

4 Answers 4

Reset to default 4

Does this work for you?

$("div > p").each(function () {
    $(this).replaceWith($(this).text() + "<br/>");
});
$("div").wrapInner("<p></p>");

https://jsfiddle/vnLnmx0c/

This is a possible solution using only javascript.

element = document.getElementById("replace"); //Replace for whatever you want
html = element.innerHTML;
html = html.replace(/<p>(.*)<\/p>/g, "$1<br />"); //$1 here contains all the html between the <p> tags. So you can change this around to what you want it to be, example: <a>$1</a>
element.innerHTML = html;
<div id="replace">
  <p>1111</p>
  <p>2222</p>
  <p>3333</p>
</div>

You can do like this:

var ps = $("#maindiv").find("p");
var par = [];
ps.each(function(index, d){
    par.push($(d).text());
});

var text = par.join("</br>");
//remove all the paragraph dom
$("#maindiv").find("p").remove();
//make aparagraph dom and add the new html text joined by </br>
$("#maindiv").append("p").html(text);

Working code here.

I have a created a fiddle for you. check it

https://jsbin./gazefa/edit?html,js,output

<button onclick="removePs('target')">Remove Multiple Ps</button>
<div id="target">
    <p>1111</p>
    <p>2222</p>
    <p>3333</p>
</div>

JS

function removePs(div_id) {
  var html = '<p>';
  $('#' + div_id + ' p').each(function(i, p) {
    html += $(p).html() + '</br>';
  });
  html += '</p>';
  $('#' + div_id).html(html);
}
发布评论

评论列表(0)

  1. 暂无评论