How can i set array of content for <p> tag with one id using javascript or jquery

Viewed 27

Here is my full code

<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>
<script>
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]);
}
</script>
</body>
</html>

Here I have to set values from array named changed_array in above code to <p> tag with id=xyz serially .

In current code in only one <p> tag value is getting set.

How can I change the values with id=xyz to <p> tag from array on webpage ?

Expected Output on webpage :

[items-carting nums="hbn7wxjxjodpxi2nlmml"] should change to "This is the value : hbn7wxjxjodpxi2nlmml"

[items-carting nums="nlmmljodhbni27wxjxpx"] should change to "This is the value : nlmmljodhbni27wxjxpx"

[items-carting nums="bni27wxjnlmmljodhxpx"] should cange to :This is the value : bni27wxjnlmmljodhxpx"

But currently i am getting following output:

This is the value : bni27wxjnlmmljodhxpx to be saved

[items-carting nums="nlmmljodhbni27wxjxpx"]

[items-carting nums="bni27wxjnlmmljodhxpx"]

product design

vmware

1 Answers

Use a classname instead of id. id must always be unique, whereas classname can be shared across multiple elements.

var all=$("p:contains(" + userInput + ")").addClass('xyz');
for (var j = 0; j < changed_array.length; j++) {
$(".xyz").eq(j).text(changed_array[j]);
}

Here is a more thorough explanation on the differences between class and id if you'd like one.

Related