We can use JavaScript's "createElement" method to create a new element. We can then add that element to the parent element on the HTML page using the "appendChild" method. To position an element horizontally, we can use CSS styles on the newly created element, such as "display:inline-block" or "float:left/right".
Suppose we want to describe a graphical representation of a linked list data structure. Whenever the user clicks the button, a new node (in our case represented by a green circle) should be added horizontally to the front of the node list.
And the text inside that green circle should be the index of that specific node.
The method here is very simple and straightforward-
We will create a button that will be responsible for inserting a new node.
Every time the button is clicked, the node's count increases by 1.
A separate function responsible for rendering the node will then receive that count and render the node.
To render the nodes in reverse order, we set the flex-direction property of the container div to row-reverse.
This is a complete working example of this approach -
<!DOCTYPE html> <html> <head> <title>Linked List Graphic Representation</title> <style> #holder { display: flex; flex-direction: row-reverse; align-items: center; margin-top: 10px; justify-content: flex-end; overflow-x: scroll; } .element{ border-radius: 50%; background: green; color: white; height: 25px; width: 25px; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <button onclick = "handleInsert()">Insert Node</button> <div id = 'holder'></div> <script> let currentElements = 0; const handleRender = () => { const holder = document.getElementById('holder'); holder.innerHTML = ''; for (const index in Array(currentElements).fill(null)) { const element = document.createElement('div'); element.innerText = index; element.classList.add('element'); holder.appendChild(element) } }; const handleInsert = () => { currentElements++; handleRender(); }; handleRender(); </script> </body> </html>
We created a basic HTML file using JavaScript to create a simple graphical representation of a linked list. It has a button that, when clicked, calls a function that inserts a new node (element) into the linked list and updates the graphical representation.
The graphical representation is created using a div element with class name "element" and is styled into a circle. The elements are displayed in a flex container with the "id" of "holder", which is set to overflow-x: scroll so that it can be scrolled when there are too many elements in the viewport.
The above is the detailed content of How to add elements horizontally in HTML page using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!