Help me fix this script

Started by miaedwards, Sep 03, 2022, 01:43 AM

Previous topic - Next topic

miaedwardsTopic starter

A basic script that loads desired text (date) from a designated element can be rephrased as follows without losing meaning:

In the code snippet below, the desired date is loaded and displayed from a specific element with the following HTML code:

<span id="data">date loading...</span>
This is achieved using the following script:
<script>
elm = document.getElementById('data');
elm.innerHTML = "May 19, 21-00"
</script>

However, if there are numerous elements of interest on the page (such as replacing all spans designated by class="data"), a different approach must be taken. Despite the availability of document.getElementsByClassName, it may not work on all browsers, including mobile devices.
  •  

nancyfromafrica

Based on the code provided, it appears that there is an ID labeled as "data" rather than a class. Note that only one ID should be present.

To cycle through all data on the page, a script must be implemented. The following code shows a simple script to loop through desired elements with the "data" class:

<span class="data">date loading...</span>
<span class="data">date loading...</span>
<span class="data">date loading...</span>

The code below should be inserted after the desired elements in the page code, which will execute the script through all "data" elements in a loop:

<script type="text/javascript">
var elem = document.querySelectorAll('.data');
for (i = 0; i < elem.length; i++) { elm[i].innerHTML='May 19, 21-00'; }
</script>

For beginners in scripting, note that using the querySelectorAll() method can simplify searching for specific elements with designated classes. Additionally, testing scripts on multiple browsers and devices is essential to ensure cross-compatibility.
  •