Using .after to add </tr> <tr> does not work

I have a table that currently has two columns per row, and I need to split it using jQuery.

I tried this:

 $(document).ready(function() { $('.TextBold').after('</tr><tr>'); }); 

... but it does not work. I wonder if there could add <p>Test</p> instead of </tr><tr> ?

Here you can see my code in JSFiddle .. http://jsfiddle.net/QjJhU/

I would appreciate it if someone could explain the problem.

+4
source share
2 answers

The problem is that you imagine jQuery (and Javascript in general) is editing an HTML document. This is not true. The browser reads the HTML and then creates a DOM structure from it. At this point, the HTML content is completely irrelevant. The only thing that worries the browser is the structure of the DOM.

This means that you cannot add element bits: you can add whole elements (or text nodes) to a document. You try to close one tag (using </tr> ), then open another tag (with <tr> ). In fact, the browser reads </tr><tr> and outputs a DocumentFragment from it. Since the closing tag is not valid on its own, it is removed. Then <tr> turns into an entire element in itself: efficiently, <tr></tr> . This is valid HTML, so it turns into a valid DOM element and is inserted.

You need to develop a way to remove td from one tr by creating a new tr and adding td to it.

Something like this should work:

 $('.TextBold').each(function() { $('<tr/>').insertAfter(this.parentNode).append($(this).next()); }); 

It says:

  • for each TextBold element, follow these steps:
    • create a new tr element
    • insert it after parent TextBold (which is tr )
    • add the element following the TextBold to the new tr (this also TextBold it from its current position)

Here's jsFiddle with this working code .

+3
source

Try instead:

 $('.TextBold').each( function(){ $('<tr />').insertAfter($(this).parent()).append($(this).next('td')); }); 

JS Fiddle demo .

The reason your approach doesn't work is because JavaScript, and therefore jQuery, creates DOM nodes, not markup as such. Therefore, you cannot add a closing </tr> and an opening <tr> , only the DOM node, which consists of the entire node.

Regarding your question:

Interestingly, I can add <p>Test</p> instead of </tr><tr> there.

I honestly can't understand what you mean; but inside a table and outside td or th a p will make the premium invalid because p not a valid child of tbody , tfoot , thead , tr or table .


Edited to update published jQuery, replace parent() with closest() :

 $('.TextBold').each( function(){ $('<tr />').insertAfter($(this).closest('tr')).append($(this).next('td')); }); 

JS Fiddle demo .

Literature:

+2
source

Source: https://habr.com/ru/post/1394289/


All Articles