Home > Net >  How can I append dynamic text contents to the end of existing text contents based on what WAS in it
How can I append dynamic text contents to the end of existing text contents based on what WAS in it

Time:09-21

I am currently making chrome extension, and would like to display additional content to the existing website.

Given following html

<p class="c1 c2">ID 1</p>
<p class="c1 c2">ID 2</p>
...
<p class="c1 c2">ID 20</p>

I would like to append modification to the ID # and append it to the end So above example would be transformed to following

In following example result, I got the ID number and squared away the ID, then appended "SQ #" to the existing line.

<p class="c1 c2">ID 1 SQ 1</p>
<p class="c1 c2">ID 2 SQ 4</p>
...
<p class="c1 c2">ID 20 SQ 400</p>

How can I achieve this?

I tried to use the $(".c1.c2").append, but was not really successful.

I think I am both

  1. not getting the existing ID correctly.
  2. not getting the output properly formatted to be displayed (output shows up as ID 1 funciton() {...} instead of desired result

CodePudding user response:

The .text method can be used with a function argument, along with its arguments (the second of which is the old text content):

$(".c1.c2").text((_index, oldValue) => oldValue
  .replace(/ID (\d )/, (fullMatch, id) => `${fullMatch} SQ ${id ** 2}`));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="c1 c2">ID 1</p>
<p class="c1 c2">ID 2</p>
<p></p>
<p class="c1 c2">ID 19</p>
<p class="c1 c2">ID 20</p>

.replace is also used with a function argument. The regular expression /ID (\d )/ matches any "ID " followed by an arbitrary, non-negative integer. The first argument, fullMatch, is reused, and " SQ " followed by the squared integer is appended using template literals.


My take on a vanilla JS alternative:

document.querySelectorAll(".c1.c2")
  .forEach((elem) => elem.textContent = elem.textContent
    .replace(/ID (\d )/, (fullMatch, id) => `${fullMatch} SQ ${id ** 2}`));

CodePudding user response:

With plain js::

document.querySelectorAll('.c1').forEach(i => {
  i.innerText = `${i.innerText} SQ ${Number(i.innerText.slice(3, i.innerText.length))**2}`
})
<p class="c1 c2">ID 1</p>
<p class="c1 c2">ID 2</p>
<p class="c1 c2">ID 3</p>
<p class="c1 c2">ID 10</p>
<p class="c1 c2">ID 15</p>
<p class="c1 c2">ID 19</p>
<p class="c1 c2">ID 20</p>

  • Related