2

I'm using the replace function to replace a div. Using something like this:

$(document).ready(function() {
  $("#electricalengineering").click(function() {
    $("#section1").replaceWith("#section2");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="section1">
  <p>First Div</p>
  <a href="#">
    <p id="electricalengineering">Electrical Engineering</p>
  </a>
</div>
<div id="section2">
  <p>Second Div</p>
</div>

Strangely, upon clicking, the #section2 is visible as text. Any ideas?

Here is the Working Example

j08691
  • 204,283
  • 31
  • 260
  • 272
Beck
  • 51
  • 6

2 Answers2

1

When passing "#section2" you are passing a string not the content of #section2

try passing it a jquery object instead

$("#section1").replaceWith($("#section2"));
imvain2
  • 15,480
  • 1
  • 16
  • 21
1

You are passing a string, rather than the jquery object you were planning on.

Rather than "#section2" replace it with $("#section2") as below.

$(document).ready(function(){
  $("#electricalengineering").click(function(){
    $("#section1").replaceWith($("#section2"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="section1">
<p>First Div</p>
<a href="#"><p id="electricalengineering">Electrical Engineering</p></a>
</div>
<div id="section2">
<p>Second Div</p>
</div>
Oliver Trampleasure
  • 3,293
  • 1
  • 10
  • 25