Home > Enterprise >  How to select the closest element with contains selector jquery
How to select the closest element with contains selector jquery

Time:09-24

I want to replace the "{{my_name}}" and "{{my_email}}" with a string, but the program is not working, what should i do?

Thanks.

$(".notes *:contains('{{')").text(function() {
  var rawkey = $(this).text().match(/{{(.*?)}}/i)[0]; // Output (console.log) : {{my_name}} or {{my_email}}
  var key = $(this).text().match(/{{(.*?)}}/i)[1]; // Output (console.log) : my_name or my_email

  if (key.indexOf('name') > -1) {
    $(this).text($(this).text().replace(rawkey, "Tony"));
  } else if (key.indexOf('email') > -1) {
    $(this).text($(this).text().replace(rawkey, "[email protected]"));
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="notes">
  <h4>{{my_name}}</h4>
  <table>
    <tr>
      <td>
        <p>{{my_name}}, {{my_email}}</p>
      </td>
    </tr>
  </table>
</div>

CodePudding user response:

Set the result after replacing back to the element's textContent:

$(".notes *:contains('{{')").text(function() {
    var rawkey = $(this).text().match(/{{(.*?)}}/i)[0];
    var key = $(this).text().match(/{{(.*?)}}/i)[1];

    if (key.indexOf('name') > -1) {
        $(this).text($(this).text().replace(rawkey, "Tony"));
    } else if (key.indexOf('email') > -1) {
        $(this).text($(this).text().replace(rawkey, "[email protected]"));
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="notes">
  <h4>{{my_name}}</h4>
  <table>
    <tr>
      <td>
        <p>{{my_email}}</p>
      </td>
    </tr>
  </table>
</div>

CodePudding user response:

You can do like this.

 var $content=$('.notes').html();
var finalContent=$content.replaceAll("my_name","Tony").replaceAll("my_email","[email protected]").replaceAll("{{","").replaceAll("}}","");
$(".notes").html(finalContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
  <h4>{{my_name}}</h4>
  <table>
    <tr>
      <td>
        <p>{{my_name}},{{my_email}}</p>
      </td>
    </tr>
  </table>
</div>

  • Related