Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to switch wrapping elements using jQuery

Tags:

jquery

I have this code in HTML

<span id="s">Attachments</span>

How to use jQuery to switch the outer SPAN element with the following table code block, so that the "Attachments" text becomes wrapped with the table element.

<table id="t">
  <tr>
    <td>Attachments</td>
  </tr>
</table>
like image 635
Registered User Avatar asked May 06 '12 00:05

Registered User


People also ask

Which jQuery method allows you to add a wrapper element around another set of elements?

The wrap() method wraps specified HTML element(s) around each selected element.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

What is .next in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

How do you wrap two elements in a div?

You can use the . wrapAll() method.


1 Answers

You could create a table with a tr and td, insert the HTML contents from the span into that new td element, insert the table immediately after the span, and then finally, remove the span.

$("<table id='t'><tr><td>" + $("#s").html() +
    "</td></tr></table").insertAfter("#s");

$("#s").remove();

I'm assuming by "swipe" you mean "swap"? So that's why I've removed the original span. If this is not the case, just leave out the remove call.

like image 123
jmort253 Avatar answered Oct 27 '22 00:10

jmort253