jQuery : A simple tag replacement

2019-08-28 09:03发布

I just want to replace all <p> tags with <tr>

function test() {
$("p").each(function(index) {
var htmlStr = $(this).html();
$(this).replaceWith("<tr>" + htmlStr + "<\/tr>");
});
}

It's not working. the replacement does work but the html content of the <p> tags is removed. so the output would be something like <tr></tr>

Also, this function will go through all the entire html page, right ? I just want it to be processed on my #content_div. Is there anything I should add or before $("p") ?

4条回答
疯言疯语
2楼-- · 2019-08-28 09:23

I did some experimenting, and figured you could use the wrap function of jQuery to add a tag around an element. This would leave the paragraph tags in place, but that is probably not your main concern. This results in some very easy to follow code:

$("#content_div p").wrap("<tr>");

However, this makes no sense as noted in the other posts as you probably also need a TD tag as well and possibly a table tag around all the elements. Your code would then look like this:

$("#content_div p").wrapAll("<table>");
$("#content_div p").wrap("<tr><td>");
查看更多
Rolldiameter
3楼-- · 2019-08-28 09:31

You are probably seeing no content because you are creating content in a tr tag as an example here http://jsfiddle.net/Pf5n3/

For the content to show you will need to have your content in a td if you are not allready in a tr like this http://jsfiddle.net/Pf5n3/1/

查看更多
戒情不戒烟
4楼-- · 2019-08-28 09:37

it's unreliable to manipulate HTML directly via search/replace functions - any attributes in the HTML being parsed would break the code..

i'd chose to do it this way.. given any empty target table of

<table>
    <tbody></tbody>
</table>

use this javascript

function test() {
    $("p").each(function(index) {
        $("tbody").append($("<tr></tr>").html(this.innerHTML));
        $(this).remove();
    });
}

see the fiddle here

查看更多
做个烂人
5楼-- · 2019-08-28 09:48

That's because <TR> can't contain anything other than <TH> or <TD>. jsFiddle

function test() {
    $("#content_div").find('p').each(function(index) {
        var htmlStr = $(this).html();
        $(this).replaceWith("<tr><td>" + htmlStr + "</td><\/tr>");
    });
}
查看更多
登录 后发表回答