A.A. PEACE A.A. PEACE - 1 month ago 6
jQuery Question

Change title of an element via 'onclick' event using JQuery

I have the code below in the

head
section of my web app:

<script>
$(document).ready(function(){
$("#menu_s").click(function(){
$("upt").replaceWith(function(n){
return "<h2>Αρχικά Πιάτα</h2>";
});
});
$("#menu_md").click(function(){
$("upt").replaceWith(function(n){
return "<h2>Κυρίως Πιάτα</h2>";
});
});
});
</script>


and the code below (just part of it-the necessary one :)) in the
body
section:

<section>
<header>
<upt><h2>Φαγητά & Ποτά</h2></upt>
<h3>FoodBall Admin</h3>
</header>
<div id="tabs">
<ul class="ca-menu">
<li>
<a href="#starters" id="menu_s">
<span class="ca-icon">&#59;</span>
<div class="ca-content">
<h2 class="ca-main">Αρχικά Πιάτα</h2>
</div>
</a>
</li>
<li>
<a href="#main_dishes" id="menu_md">
<span class="ca-icon">&#59;</span>
<div class="ca-content">
<h2 class="ca-main">Κυρίως Πιάτα</h2>
</div>
</a>
</li>
</ul>
</div>
</section>


When I click on any of the two
href
links the title updates successfully. However, when I click a second time, nothing happens.

Any advice will be really helpful as I am stuck for a while on this.

Answer

Instead of replacing the entire upt element, you could just replace the inner HTML, like the code below:

$("upt h2").html("Κυρίως Πιάτα");  

When you replace the upt tag with the returned element of the function (i.e. <h2>...</h2>) you are basically removing the upt element from the DOM.

The first time it works (because the element is there, in the DOM) but after the first click, it gets replaced by h2 (and it's no longer there to select it for the second click)

See running demo below

 $(document).ready(function() {
   $("#menu_s").click(function() {
     $("upt h2").html("Αρχικά Πιάτα");
   });

   $("#menu_md").click(function() {
     $("upt h2").html("Κυρίως Πιάτα");
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <header>
    <upt>
      <h2>Φαγητά & Ποτά</h2>
    </upt>
    <h3>FoodBall Admin</h3>
  </header>
  <div id="tabs">
    <ul class="ca-menu">
      <li>
        <a href="#starters" id="menu_s">
          <span class="ca-icon">&#59;</span>
          <div class="ca-content">
            <h2 class="ca-main">Αρχικά Πιάτα</h2>
          </div>
        </a>
      </li>
      <li>
        <a href="#main_dishes" id="menu_md">
          <span class="ca-icon">&#59;</span>
          <div class="ca-content">
            <h2 class="ca-main">Κυρίως Πιάτα</h2>
          </div>
        </a>
      </li>
    </ul>
  </div>
</section>

Comments