Having probs with 'Target[i].setAttribute()'

Can anyone help me…
When I run the code below , I get
3 of these: ‘Target = [object HTMLOptionElement]’
and one of these: ‘Target = undefined’.

  <html>
  <head>
  <script>
  document.addEventListener("DOMContentLoaded", () => {
   alert("DOM ready!   Hit ...F12...  to Open DevTools");
  });
  let Target = [] ;
  let i = 0 ;
  function ATargetHtml() {
  // Dec  lare Target inside the function to guarantee that the list of links is up to date
  Target = document.getElementsByTagName("OPTION");
      
  for (var i = 0; i < Target.length; i++) {
   // Show the current target element in the console
   alert("Target = " + Target[i]);
   if (Target[i].hasAttribute("value")) {
    Target[i].setAttribute("value", "http://vmars.us");
   }    
  }    
   alert("Target = " + Target.length[i]);
   alert('<!DOCTYPE HTML>' + '\n' + document.documentElement.outerHTML);
  }     
  </script>
  </head>
  <body>
  	<h3>Accessing HTML 'option' of a DOM element in JavaScript .</h3>
  <p>
  <a href="https://www.kirupa.com/" target="_blank">https://www.kirupa.com/" target="_blank</a>
  <br>
  <a href="https://www.kirupa.com/" target="_top">https://www.kirupa.com/" target="_top</a>
  <br>
  <a href="https://www.kirupa.com/" target="_self">https://www.kirupa.com/" target="_self</a>
  </p>
  <p>
  <select style="width:200px; font:14px Arial Black; color:rgb(0,0,0); background-color:rgb(214,226,255);" name="menu" onchange="window.open(this.value); window.location.reload();">
   <option selected="0" value="">aaDaily</option>
  <option value="https://www.sitepoint.com/community/categories">Categories</option>
  <option value="https://www.sitepoint.com/community/faq">FAQ</option>
  </select>
  </p>
  	<br>
  	<button onclick="ATargetHtml()">
  		Get and change the html for DOM element
  	</button>
  <br>
  </body>   
  </html>```   
Thanks

For whatever reason the browser gods have decreed alert() has priority is the callstack.

So if in your for loop you put a console.log(i) above the alert() you will see 0 1 2 logged but not 3 (fourth iteration) and you will still see a fourth alert() (which is now undefined)

Somehow the alert can jump the gun before your for loop evaluates the i < Target.length and jump the que in front of any code in the loop block.

I once built a mutationObserver that would see if any script had been injected into the DOM and immediately remove the script before executing.
It worked fine and would kill the script before any code could run… except alert().
It was the only code that would jump the que and evaluate…

Alert also blocks any JS running until it has been clicked.

Very interesting Steve , Thanks

1 Like