Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add element before some element

Tags:

jquery

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>
like image 947
vinanghinguyen Avatar asked Feb 28 '12 02:02

vinanghinguyen


People also ask

How do you add an element before another element?

Insert an Element Before AnotherThe insertBefore() function selects the parent element of the existing node and calls the insertBefore() method to insert the new node before the existing node.

How do you prepend an element in JavaScript?

prepend() The Element. prepend() method inserts a set of Node objects or string objects before the first child of the Element . String objects are inserted as equivalent Text nodes.

Is there a prependChild in JavaScript?

There's no prependChild , but prepending can be done using the insertBefore() .


2 Answers

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.....

like image 89
Anil D Avatar answered Oct 04 '22 20:10

Anil D


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>.

like image 42
James Montagne Avatar answered Oct 04 '22 19:10

James Montagne