3
12 Comments

Learning to code question - What is the best way to update a bunch of elements on a page?

Using just HTML and Javascript. I have experience in Swift and iOS but still really new to web dev. I have a little calculator where a user enters some info. I use that info to calculate some things, then display those in a few places down the page. I often display the same piece of info in a couple different sections.

How I am currently doing this is in the HTML I am using a lot of <span name=nameOfElement>

Then in the js file I grab those elements with something like this:

listOfElements = document.getElementsByName('nameOfElement');

I then use a for loop to go through each of those and set the textContent.

for (var i = listOfElements.length - 1; i >= 0; i--) {
listOfElements[i].textContent = calcValue; }

Is there a better way to do this?

on February 3, 2020
  1. 3

    Hey Josh, you are on the right track. However, 'name' attributes are mostly used on form elements, like input, textarea, select etc.

    Rather use classes on html elements you want to style or select and update via Javascript.

    Example:

    var myClasses = document.getElementsByClassName("replaceThis");

    <div class="replaceThis">something i want to replace</div>
    <div class="replaceThis">something i want to replace</div>
    <div class="replaceThis">something i want to replace</div>

    <script>
    for (var i = 0; i < myClasses.length; i++) {
    myClasses[i].innerHTML = "new content";
    }
    </script>

    OR, if you want to use jQuery ( jQuery is a wrapper library for JS functions, and makes things a little easier for newcomers to JS. You can select html elements in the DOM by using CSS selectors like '.className' or '#idName'. You can learn jQuery here https://www.tutorialspoint.com/jquery/index.htm )

    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
    <div class="replaceThis">something i want to replace</div>
    <div class="replaceThis">something i want to replace</div>
    <div class="replaceThis">something i want to replace</div>

      <script>
           $('.replaceThis').html('new content');
      </script>
    

    </body>
    </html>

    1. 2

      Ah yes, I didn’t catch that. You’re right, ids and classes are usually used as selectors.

    2. 1

      Awesome I will make this change. Thank you.

  2. 2

    of the three mentioned (react/vue/svelte) I think react has the biggest community built around it.

    to answer your question specifically though, you can use something like listOfElements.forEach(element => element.textContent = calcValue)

    In Javascript no one uses for loops almost ever. And most people use something like React.

    Let's meet up sometime and I can drop some hot tips since we already know each other IRL.

    1. 1

      Thanks! Totally forgot about the forEach.

      And dude good to see you on IH! Didn't recognize your username. Let's meet up.

  3. 2

    That's a perfectly fine way of doing things for small applications (although it's more standard to use a class or ID for selections), but I'm betting you can see how it would get difficult as the application grows and the rules for updating the DOM become more complex.

    Most modern applications use some sort of data binding, you'll see this in popular frameworks like React or Vue. Basically, the DOM element is bound to some sort of state variable, and as that gets update the framework takes care of updating all elements where that var is output. This makes tasks like this easier and much less prone to error. Just something to keep in mind!

    1. 2

      Thank you! I will make the change to a class.

      Question about class vs id.

      classes can be applied to many elements. Ids are supposed to be unique to each html element I thought. Is that true?

      Funny story, as I was working on this, I thought 'I need a way to create html elements with javascript so they would be linked automatically'

      I started thinking of ways to do this, then it hit me. I think I just invented React. :)

      You have confirmed where my thoughts were going about this. Thank you!

      1. 2

        From what I researched, id's need to be unique. Since I want to repeat the same piece of data on the page a few times, class looks like the way to go for me. Thanks! https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page/9454716#9454716

    2. 1

      Interesting hiccup. https://stackoverflow.com/questions/60090148/why-does-document-getelementsbyname-return-a-nodelist-while-document-getelements

      So while I was switching to use classes, I had to change how I accessed the results.

      I was using a forEach on the results of the getElementsByName which returned an array.

      But the getElementsByClassName returns an 'array like' structure that I then have to put into an array.

      const activityListElements = document.getElementsByClassName('activity');
      const activityList = Array.from(activityListElements);
      activityList.forEach( function(element, index) {
      element,addEventListener('click', activeMultipler);
      });

      I figured it out but couldn't understand why it was failing for a while. :)

  4. 2

    If you want to have data binding similar to your experience with iOS you may want to consider using a framework like React, Vue, or Svelte.

    If you scroll down a bit on this page you can see an example of data binding in Svelte.

    1. 1

      Thank you! I was thinking I was going to have to move to some sort of data binding idea. You confirmed that direction for me.

      svelte looks interested, hadn't really heard about it before.