Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing a specific word within div after it being applied

I have got a div

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
            <div class="div">
              <div class="subdiv">
                <p>${Groups[0].Names[0].Nickname}</p>
              </div>
            </div>
            <div class="div">
              <div class="subdiv">
                <p>${Groups[0].Names[1].Nickname}</p>
              </div>
            </div>
</html>

My goal is to replace "Nickname" with "Coolname" for each div after clicking a button, however the page loads up with Nickname by default and if I execute jquery $('#subdiv p').text((i, t) => t.replace('Nickname', 'Coolname')); it doesn’t actually see "Nickname" but the output itself. Is there any simple workaround? preferably without jquery. I simply need to change Nickname with Coolname and then display it again as Groups[0].Names[0].Coolname

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Obviously you are using a template engine in the backend. jQuery in the frontend does not know "Coolname" after rendering the HTML page. But you can specify this value in a data attribute and let jQuery access it.

In this example, nickname and coolname are not changed, but you could implement it like this or similar:

$('#change').on('click', function() {
  $('[data-coolname]').each(function() {
    $(this).html($(this).attr('data-coolname'));
  });
});
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <div class="div">
    <div class="subdiv">
      <p data-coolname="${Groups[0].Names[0].Coolname}">${Groups[0].Names[0].Nickname}</p>
    </div>
  </div>
  <div class="div">
    <div class="subdiv">
       <p data-coolname="${Groups[0].Names[1].Coolname}">${Groups[0].Names[1].Nickname}</p>
    </div>
  </div>
  <button id="change">change</button>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading