Home > OS >  jQuery .after() that replaces instead of appends
jQuery .after() that replaces instead of appends

Time:12-03

I have the following test. You'll notice hi and hello were both added. What I need is for hi to be replaced with hello. As a follow-up question, is there a way to get the value of the .after()?

$("#test").after("hi");
$("#test").after("hello");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=test>TEST</div>

CodePudding user response:

Add a span after your div and give it a class name. Then just reference that class name from after that. Since you have given it a class name, you can easily get the HTML of that span.

$("#test").after("<span class='subTitle' />");

$(".subTitle").html("HI");
$(".subTitle").html("Hello");

console.log($(".subTitle").html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">TEST</div>

  • Related