Search code examples
jqueryreplacewith

Section ID id is Visible in text with jquery replace function


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


Solution

  • 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>