jQuery : A simple tag replacement

2019-08-28 09:06发布

问题:

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") ?

回答1:

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>");
    });
}


回答2:

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/



回答3:

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



回答4:

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>");