Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting this output? ( jQuery .append() issue)

Why append is behaving quite differently here..can anybody explain this!

Recently while practicing jQuery got stuck here, Didn't understand what was happening: On the first button click the elements are getting appended normally as expected but on/after second click things(Output) are starting to get weird. Can someone please explain what is happening here...
I am new to jQuery.

function appendText() {
  var txt1 = "<p id='set'>Text1</p>";
  console.log("Text1", txt1);

  var txt2 = $("<p></p>").text("Text2");
  console.log("Text2", txt2);

  var txt3 = document.createElement("p");
  txt3.innerHTML = "Text3";
  console.log("Text3", txt3);

  var txt4 = $("#set").html("Text4");
  console.log("Text4", txt4);

  $("body").append(txt1, txt2, txt3, txt4);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Append Test Example</p>
<button onclick="appendText()">Append text</button>

Output Image

like image 265
K R Y Avatar asked Dec 22 '25 08:12

K R Y


1 Answers

try this?

var ourButton = document.getElementById("btn");
    
var ourList = document.getElementById("our-list");

ourButton.addEventListener("click",func2);

newAddedText = 1;

function func2() {
  ourList.innerHTML += "<li>anything " + newAddedText + "</li>";
  newAddedText++;
}
<button id="btn">Add New</button>
<ul id="our-list">
</ul>
like image 137
doğukan Avatar answered Dec 23 '25 21:12

doğukan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!