What causes JavaScript to not execute sequentially?

Here is some HTML/JavaScript code, but when the function calc() is called, it outputs an <ol> tag first, rather than running the script in order. I have removed the setTimeout() function to make it run synchronously.

If anyone can provide an explanation, it would be greatly appreciated.

function $(id) {
  return document.getElementById(id);
}
regex_field = $('regx');
content = $('content');
output = $('output');
flag_field = $('flag')


flag_field.addEventListener('input', function() {
  calc();
});
content.addEventListener('input', function() {
  calc();
});
regex_field.addEventListener('input', function() {
  calc();
});

function calc() {
  var re = new RegExp(regex_field.value, flag_field.value)
  console.log(re);
  found = content.value.match(re);
  if (found) {
    $('output').innerHTML = "<ol>";
    for (let i = 0; i < found.length; i++) {
      $('output').innerHTML += '<li>' + found[i] + '</li>';
    }
    $('output').innerHTML += "</ol>";
  } else {
    $('output').innerHTML = "Nothing Found!";
  }

}
<html>

<head>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
</head>

<body>


  <div class="row">
    <div class="col-sm-6 form-inline">
      RegExp
      <input class="col-sm-4 form-control form-control-sm" type="text" id="regx" placeholder="Regex Input"> Flag
      <input class="col-sm-1 form-control form-control-sm" type="text" id="flag">
      <br>
      <div>
        <p>Input Content</p>
        <textarea class="form-control col-sm-12" name="input" placeholder="Text" id="content" cols="30" rows="10"></textarea>
      </div>
    </div>
    <div class="col-sm-6">
      <p>Content get</p>
      <div id="output"></div>
    </div>
  </div>


</body>

</html>

The output appears as shown below. I am unsure why the 'ol' tag comes before the 'li' tags.

<div id="output">
  <ol></ol> //  <---  question here
  <li>12</li>
  <li>34</li>
</div>

Answer №1

When the code

$('output').innerHTML = "<ol>";
is executed, it immediately inserts the ol tag into the element with the id of output. However, as an <ol> tag without a closing </ol> is invalid, the DOM automatically closes it for you. The result will be:

<div id="output">
    <ol></ol>
</div>

Subsequently, when you run

$('output').innerHTML += '<li>' + found[i] + '</li>';
, it appends that line to the content of the element with the id of output. This is also invalid markup because an li cannot be nested inside a div, but the browser attempts to correct it in this way:

<div id="output">
    <ol></ol>
    <li>12</li>
</div>

The preferred approach is to construct the innerHTML content and then update it all at once, like so:

if (found) {
    var output = '';
    output = "<ol>";
    for (let i = 0; i < found.length; i++) {
       output += '<li>' + found[i] + '</li>';
    }
    output += "</ol>";
} else {
    output = "Nothing Found!";
}
$('output').innerHTML = output;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for extracting the right content without disrupting HTML tags by combining strip_tags and substr functions

Within my webpage, I display previews of posts sourced from RSS feeds. Each preview consists of approximately 300 characters. Upon clicking on an expand button, the #post-preview is then swapped out with the full #post. However, the format of the #post is ...

Executing a web API call during the initialization of a Node.js server

After creating a web API for a specific task, I encountered an issue where I could not hit the API at server startup. I used the following method: var request = require('request'); request('http://localhost:3000/api/jobs/asd', func ...

Utilizing DT::datatable to Display Grouped DataFrame in an Rmarkdown Report (HTML)

I am trying to display a grouped data frame output in an interactive DT::datatable with Download buttons (csv,excel) within my Rmarkdown report (HTML). Everything works smoothly until I encounter an error stating that there is no group by method applicabl ...

Issues encountered when executing unit tests using karma

I encountered these issues in the logs. Seeking advice on how to proceed. Thank you. I've attempted uninstalling and reinstalling phantomjs, clearing out my node modules and bower component directories. Everything was functioning as expected before, a ...

Ways to send a variable to a component through history.replace

Is there a way to retrieve the match.chatroomId in a functional component? I am currently using history.replace to navigate to this component. Here is the code snippet: onClick = {() => history.replace(`/chat/${match.chatroomId}`)} ...

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

How can I troubleshoot the issue with generating a Shortid field automatically in an object array on MongoDB?

I tried to write a query to retrieve an array of specific objects, but it returned all documents instead. Here is the object structure: { "_id" : ObjectId("5a253ae1c14d9573f1f91088"), "accountId" : 1, "regionId" : "1", "problemId" ...

Exploring outside iframe data

My webpage includes an iframe A with a src attribute that links to a URL containing another embedded iframe B. I'm trying to figure out if it's possible to access the src of this nested iframe B. However, it appears that browser security measures ...

Tips for refreshing a controller in Angular

I am working on a categoriesPanel controller where, upon clicking using ng-click, I want to display all the products belonging to that category inside my ng-controller productsPanel. However, I am facing an issue - every time I click on ng-click="selectorC ...

Aptana's Smart Code Completion

Does Aptana offer code completion for custom JavaScript libraries? If so, how can we enable it? ...

Tips for displaying multiple videos on an HTML webpage

I am trying to set up a video player for videos in 720p resolution (1280x720) with autoplay and looping so that once one video ends, the next one from an array will start playing. However, I am encountering issues where the first video does not autoplay an ...

AngularJS Tutorial: Storing the Index Position of a JSON Object without Saving the Object Itself

My JSON data is as follows: $scope.myjson = [ {id: "1", name: "a"}, {id: "2", name: "b"}, {id: "3", name: "c", children: [{id: "4", name: "d"}]} ]; I am looking to store the position ...

Setting up Tipsy with titlesorting

Recently, I attempted to incorporate the Tipsy jQuery plugin into my website to display title tags as attractive tooltips. However, I am facing issues with the plugin not working correctly. Can anyone offer assistance with this? Specifically, I am looking ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

Tips for dynamically adding an HTML element to index.html using JavaScript

https://i.sstatic.net/cAna8.png How can I use JavaScript to insert cards into a container or display them in flex? Currently, the cards are not displaying as desired. I attempted to insert data into the note class using insertAdjacentHTML in JavaScript, b ...

retrieve information originating from Firebase

I am trying to access data from this link: . The data is in JSON format and here is a snippet of how it appears: { "-MzJLd0sSssh9tbJbjUS" : { "orderDetails" : [ { "amount" : 4, "id" : "m1&q ...

Rotating an arrow image on an accordion using jQuery

I have been working on this page located at Unfortunately, my attempts to showcase the issue in a jsfiddle were unsuccessful. The webpage features an accordion-style FAQ section, and I am attempting to make the arrow rotate 90 degrees when a question is ...

Is there a way to automatically set all object properties to false if one property is set to true in React?

The Issue: My task at work involves creating 3 buttons with separate filters to display different tickets in a table. All the functionality is completed, and the filtered tickets are displayed correctly. However, I am facing an issue that is preventing m ...

Is it possible to convert a webpage into an image file using PHP?

Is there a way to save a webpage as an image file or capture a snapshot of a webpage using PHP, similar to how the Firefox extension Fireshot does? ...

"Step-by-Step Guide: Implementing a Modal Popup Form in Angular with NgBootstrap and FormsModule

I am seeking assistance with my Angular project. I am attempting to implement a Modal Popup Form using NgBootstrap and FormsModule, but encountering issues with the NgbModule not being imported. Here are some details of my setup: node 16.15.1 cli 15.1.5 co ...