Latest web development tutorials

jQuery add elements

By jQuery, you can easily add new elements / content.


Add a new HTML content

We will learn to add new content for four jQuery method:

  • append () - Insert at the end of the selected element
  • prepend () - Insert at the beginning of the selected element
  • after () - Insert after being selected elements
  • before () - Insert before selected elements

jQuery append () method

jQuery append () method inserts the contents at the end of the selected element.

Examples

. $ ( "P") append ( " append text");

try it"


jQuery prepend () method

jQuery prepend () method inserts the contents at the beginning of the selected element.

Examples

. $ ( "P") prepend ( " append text at the beginning");

try it"


Add several new elements by append () and prepend () method

In the above example, we are only at the beginning of the selected element / end insert text / HTML.

However, append () and prepend () method can receive an unlimited number of new elements by the parameter. You can generate a text / HTML (as in the example above) by jQuery, or through JavaScript code and DOM elements.

In the following example, we create several new elements. These elements can be created using text / HTML, jQuery or JavaScript / DOM. Then we append () method of these new elements added to the text (for prepend () equally effective):

Examples

function appendText () { var txt1 = ". <p> text </ p>"; // create text using HTML tags var . txt2 = $ ( "<p > </ p>") text ( " text."); // create text using jQuery var . txt3 = document createElement ( "p ");. txt3 innerHTML = " text."; // create text using text with DOM DOM $ ( "Body") append ( txt1, txt2, txt3);. // Append the new element }

try it"


jQuery after () and before () method

jQuery after () method to insert content after the selected element.

jQuery before () method before the selected element insertions.

Examples

$ ( "Img") after ( " after the Add Text");. $ ( "Img ") before ( " add text in front");

try it"


By adding a number of new elements after () and before () method

after () and before () method can receive an unlimited number of new elements by the parameter. You can create new elements via text / HTML, jQuery or JavaScript / DOM.

In the following example, we create several new elements. These elements can be created using text / HTML, jQuery or JavaScript / DOM. We then after () methods of these new elements into the text (of before () equally effective):

Examples

function afterText () { var txt1 = "<b> I < / b>"; // create elements using HTML var txt2 = $ ( "<i> </ i>") text ( "love");. // create elements using jQuery var txt3 = document createElement ( "big" );. // create elements using the DOM txt3 innerHTML = "jQuery!"; . $ ( "img") after (txt1, txt2, txt3);. // add text in the image }

try it"