2

first i was able to change
<p id="test">here what i want to replace</p>
to <p id="test">successfully replaced</p>
with

var txt1 = "successfully replaced"; document.getElementById('test').innerText = txt1;

and now i want to replace multiple <p> but with effective/shortway using arrays, like this

var txt1 [success1:"successfully replaced 1",
      success2:"successfully replaced 2",
      success3:"successfully replaced 3"];

but when i reload the browser i didn't see any changes on that <p>
i just started learning javascript last week so I'm still not sure about that

Musadarj
  • 62
  • 3
  • 9
  • 2
    Why do you think the changes will stay after reloading the browser? Is that what you would like? – evolutionxbox Jan 19 '22 at 18:41
  • You can give each element a class using `class="test"` instead of an id (because ids should be globally unique). Then you can select your elements in javascript with this code: `const elements = document.getElementsByClassName('test')`. After that, iterate over them using `elements.forEach((el, i) => { el.innerText = 'Successfully changed ' + i; })`. – MauriceNino Jan 19 '22 at 18:44
  • 1
    https://jsfiddle.net/27go3c6f/ – Andy Jan 19 '22 at 18:48
  • 1
    @Andy many thanks you for your example, it works like a charm! just change the `div` to `p` and `textContent` to `innerText` then all matches id changed. – Musadarj Jan 19 '22 at 20:35
  • 1
    Glad to help @Musadarj. Happy coding! – Andy Jan 19 '22 at 21:17

1 Answers1

-1

Use a JavaScript object as a dictionary to get the new value for each p tag.

jsfiddle: https://jsfiddle.net/bd35xov9/8/

Nolan Carpenter
  • 120
  • 1
  • 9
  • 1
    JavaScript doesn't have dictionaries – evolutionxbox Jan 19 '22 at 18:46
  • Actually, a JavaScript object can be used in place of a dictionary. – Nolan Carpenter Jan 19 '22 at 18:47
  • 1
    it sure can, but it's best to use the standard JavaScript nomenclature. – evolutionxbox Jan 19 '22 at 18:49
  • Is it? If you were to use an array and assign each value according to its index, it would be very annoying to have to reorder your array. This way you are getting the value based on the tag's name. – Nolan Carpenter Jan 19 '22 at 18:51
  • i don't want to down vote, but your example just pointing at one target (class only) and yeah somehow hard to understand to be honest. – Musadarj Jan 19 '22 at 20:58
  • 1
    @evolutionxbox but sometimes it's easier to explain things to people where the "dictionary" is an easy concept, and then provide documentation for [how to work with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) for example. Dictionaries are easy to understand. Every country has one. What is a dictionary if not key/value pairs? – Andy Jan 19 '22 at 21:20