Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

jQuery - Add Elements

//append()
$("p").append("Some appended text.");

//prepend() 
$("p").prepend("Some prepended text.");

//after()
$("img").after("Some text after")

//before()
$("img").before("Some text before");

//Add Several New Elements With append() and prepend()
function appendText() {
  var txt1 = "<p>Text.</p>";               // Create element with HTML 
  var txt2 = $("<p></p>").text("Text.");   // Create with jQuery
  var txt3 = document.createElement("p");  // Create with DOM
  txt3.innerHTML = "Text.";
  $("body").append(txt1, txt2, txt3);      // Append the new elements
}

//Add Several New Elements With after() and before()
function afterText() {
  var txt1 = "<b>I </b>";                    // Create element with HTML 
  var txt2 = $("<i></i>").text("love ");     // Create with jQuery
  var txt3 = document.createElement("b");    // Create with DOM
  txt3.innerHTML = "jQuery!";
  $("img").after(txt1, txt2, txt3);          // Insert new elements after <img>
}
 
PREVIOUS NEXT
Tagged: #jQuery #Add #Elements
ADD COMMENT
Topic
Name
8+9 =