vinanghinguyen
vinanghinguyen

Reputation: 1233

add element before some element

I have this code:

<td>
    <div id="vB_Editor_QR_cmd_email" class="imagebutton">
      abc
    </div>
</td>

I want put another element to this code like this:

<p>blablablalblablab</p>
 <td>
    <div id="vB_Editor_QR_cmd_email" class="imagebutton">
       abc
     </div>
 </td>

I use this code

 $("#vB_Editor_QR_cmd_insertimage").before("<p>blablablalblablab</p>");

but it only put before div tag.

 <td>
    <p>blablablalblablab</p>
    <div id="vB_Editor_QR_cmd_email" class="imagebutton">
       abc
     </div>
 </td>

I want it like this

 <p>blablablalblablab</p>
     <td>
        <div id="vB_Editor_QR_cmd_email" class="imagebutton">
           abc
         </div>
     </td>

Upvotes: 11

Views: 27643

Answers (3)

Anil D
Anil D

Reputation: 2009

Try this,

$("#vB_Editor_QR_cmd_insertimage").parents("td:first").before("<p>blablablalblablab</p>");

parents("td:first") will return first parent of div

hope this help.....

Upvotes: 11

Greg Franko
Greg Franko

Reputation: 1770

This selects the td element that has a nested div with an id of vB_Editor_QR_cmd_insertimage. It also provides a cleaner way to create an html element (that jQuery provides)

$("div#vB_Editor_QR_cmd_insertimage").closest("td")
.before($("<p/>", { text: "blablablalblablab" }));

Upvotes: 1

James Montagne
James Montagne

Reputation: 78650

Use before or insertBefore to place an element before another.

$("<p>blablablalblablab</p>").insertBefore("td");

or

$("td").insertBefore("<p>blablablalblablab</p>");

or more specifical to your html:

$("vB_Editor_QR_cmd_email").parent("td").before(...);

Though unless this is just a (bad) example, this is invalid. You can't have a <p> tag directly before a <td> because that would imply that the <p> is within a <tr>.

Upvotes: 7

Related Questions