How do i set all elements of array sequentially to the multiple <p> tags

Viewed 41

Only last element of an array is getting set to <p> tag

Here is my HTML , Javascript , JQuery code

var userInput = "items-carting";
var all_script = "This is the value : ";
var all=$("p:contains(" + userInput + ")").attr('id', 'xyz');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
  all_array.push($(all[i]).text());
}
all_array = all_array.filter(item => item);
changed_array=[];
for (var i = 0; i < all_array.length; i++) 
{ 
var indexEqu=all_array[i].indexOf("=");
var slicedVal=all_array[i].slice(indexEqu+2,indexEqu+22);
var result = all_array[i].replace(all_array[i],all_script);
var out=result+slicedVal+" to be saved";
changed_array.push(out);
}

for (var j = 0; j < changed_array.length; j++) {
$("#xyz").text(changed_array[j]);
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p>[items-carting nums="hbn7wxjxjodpxi2nlmml"]</p>
<p>[items-carting nums="nlmmljodhbni27wxjxpx"]</p>
<p>[items-carting nums="bni27wxjnlmmljodhxpx"]</p>
<p>product design</p>
<p>vmware</p>
</body>

</html>

Expected output is

This is the value : hbn7wxjxjodpxi2nlmml to be saved

This is the value : nlmmljodhbni27wxjxpx to be saved

This is the value : bni27wxjnlmmljodhxpx to be saved

product design

vmware
1 Answers

IDs need to be unique

This will work better

const userInput = "items-carting";
// $("p:contains(" + userInput + ")")
// .html((i,text) => `This is the value : ${text.match(/nums="(.*)"/)[1]} to be saved`)

$("p:contains(" + userInput + ")")
 .html(function() { return `This is the value : ${this.textContent.match(/nums="(.*)"/)[1]} to be saved` })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>[items-carting nums="hbn7wxjxjodpxi2nlmml"]</p>
<p>[items-carting nums="nlmmljodhbni27wxjxpx"]</p>
<p>[items-carting nums="bni27wxjnlmmljodhxpx"]</p>
<p>product design</p>
<p>vmware</p>

Or if you want it the long way around

var userInput = "items-carting";
var all_script = "This is the value : ";
$("p:contains(" + userInput + ")")
  .addClass('xyz')
  .map((_,item) => item.textContent.trim())
  .get()
  .filter(item => item)
  .map(item => {
    var indexEqu = item.indexOf("=");
    var slicedVal = item.slice(indexEqu + 2, indexEqu + 22);
    var result = item.replace(item, all_script);
    return result + slicedVal + " to be saved";
  })
  .forEach((item, i) => $(".xyz").eq(i).text(item));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>[items-carting nums="hbn7wxjxjodpxi2nlmml"]</p>
<p>[items-carting nums="nlmmljodhbni27wxjxpx"]</p>
<p>[items-carting nums="bni27wxjnlmmljodhxpx"]</p>
<p>product design</p>
<p>vmware</p>

Related