Creating Dynamic Elements in JavaScript: A Step-by-Step Guide

I've been grappling with the challenge of dynamically generating <a> tags for each Subheading (h2 element) on my blog and then populating those tags with the text from the Subheadings.

Here's what I've attempted so far:

<script>

            const subheadings = document.querySelectorAll("h2");
            subheadings.forEach(function(x) {
              document.getElementById("contents").innerHTML=x;
              <a href='#' id="contents"></a>
            });
              
</script>

Unfortunately, this didn't yield any visible results.

Any guidance or recommendations on where to focus my efforts would be greatly welcomed.

*** EDIT ***

I have incorporated the code snippet provided in one of the responses. Here's the updated version:

<div class="col-3" id="contents-table">
          <script>

            const subheading = document.querySelectorAll('h2');
            subheading.forEach(function(x) {              
              let xbe = x.innerText.split(' ');
              for (let i = 0; i<xbe.length;i++) {
              const div = document.getElementById('contents-table');
              let a = document.createElement('a');
              a.innerText = xbe[i];
              console.log( a.innerText); 
              div.append(a);
              }
                });
              
          </script>
        </div>

I trust that this update contains all the pertinent details.

However, although it follows what seems to be the correct logic, it still doesn't render the text of the h2 elements as intended.

Answer №1

html:

<h2>
    unique rephrased text example!
  unique rephrased text example!
  unique rephrased text example!
</h2>
<div class="container"></div>

css:

.holder {
 
  width:1200px;
  height:20px;
  display: flex;
}

js:

const subheading = document.querySelectorAll('h2');
const cont = document.querySelector('.container')
 subheading.forEach(function(x) {  
   cont.innerHTML = ''
   let xbe = x.innerText.split(' ');
   for (let i = 0; i<xbe.length;i++) {
   const test = document.createElement('div');
     test.classList.add('holder')
     let a = document.createElement('a');
     a.href=''
     a.innerText = xbe[i];
     console.log(a); 
     test.append(a);
     cont.append(test)
  }
   
    });

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

Arranging cards in a row using HTML or CSS for a dynamic reveal effect

Could someone assist me with my HTML code? I am struggling to figure out why my two cards are not displaying side by side on my webpage. I would also like them to be able to resize based on the size of the page. In the past, I was able to achieve this wi ...

Angular: What is the best way to pass usersearch-input data to a different component and use it to generate a list of search results?

Seeking assistance as a beginner in Angular, I am currently working on my first project with Angular 8 for the frontend of an application. The challenge I faced was creating an HTML page (...stuff/searches) where users can input search criteria to find sp ...

Adding or changing class in Angular 2 based on specific conditions

Currently, my focus is on building a web application using Angular and the Semantic-UI framework. In order to add a single class to an element based on a specific condition, I have successfully implemented the following syntax: [class.className]='co ...

hyperlink to choose a specific option from a drop-down menu

The challenge I am currently working on involves page1.html <a href="/foo"></a> foo.html <select ng-model="ctrl.listvalues"> <option id="{{item.value}}" ng-repeat="item" in ctrl.availableValues" value="{{item.value}}">item.di ...

Slideshow plugin glitch on Safari and Opera caused by jQuery implementation

My current project involves utilizing a fantastic plugin called Sequence.js for creating animations and transitions with CSS3 based on jQuery. I have set up a simple responsive fadeIn-fadeOut slideshow using this plugin. While everything works smoothly an ...

Creating a Stylish Side Navigation and Content Layout with Materialize CSS

Seeking assistance with my portfolio design using Materialize CSS, I am encountering some issues. The current appearance of my website can be seen in the screenshot below: https://i.sstatic.net/ey5SV.png The problem lies in the positioning of the About s ...

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

__dirname value not able to be retrieved

Currently, I'm utilizing __dirname to obtain the absolute path to the GraphQL schema: const schema = loadSchemaSync(path.join(__dirname, './graphql/schemas/schema.graphql'), { loaders: [new GraphQLFileLoader()] }); After transitioning the ...

Combining arrays in Javascript without using the concat method

I am facing a challenge with merging two arrays. Most solutions I have come across suggest using the concat method. However, my requirement is to add a key/value pair from array1 to each object in array2. The first array (array1) that needs to be merged: ...

How to use a jQuery selector to retrieve the value of an element that is located near another element

I am dealing with the following HTML code snippet. In my JavaScript, I have an HTML element with the id <input id = "Test[0]name">. My next task is to retrieve the value of the select element that has an id ending with "address". <div> < ...

Sending back the requested information in C to the ajax (jquery) CGI

After fetching specific data using C in my jQuery, how can I appropriately transfer the data to C? function Run() { $.ajaxSetup({ cache: false }); var obj = {"method":"pref-get","arguments":{"infos":["sys_info"]}}; alert("Post Json:" + JSO ...

What is the best way to pinpoint the origin of the element.style being injected by JavaScript?

I've been tasked with updating a client's WordPress website, but I'm still getting acquainted with the overall structure of the site. When looking at the blog page (), I noticed that posts are displayed within a wrapper labeled #blogleft, a ...

Issue arises after injecting HTML element into the DOM due to memory constraints and display inconsistencies

Upon executing the following script in Firefox... var d = $("<div class='test'></div>"); d.hide(); $("body").prepend(d); d.show(); ...and examining the HTML, the inserted element will have the style attribute: style="display: blo ...

Issues arising from utilizing Twitter Bootstrap 3.1.x, the box-sizing property, and Revolution Slider

I'm currently working on a PyroCMS theme that is built with Twitter Bootstrap 3.1.x and includes Revolution Slider. However, I've encountered an issue where the property box-sizing: border-box; creates an unwanted grey border as shown in the imag ...

What are the steps to personalize Twitter Bootstrap with Less for changing the height of the Navbar?

I recently stumbled upon some interesting articles that explain how to customize various elements of Twitter Bootstrap using LESS. You can check out one of the articles here and find more information about Twitter Bootstrap here. However, I am still unsure ...

What could be causing the discrepancy in the model value when using checkboxes in AngularJS?

Something strange is happening with my code. I have a checkbox in my view that has a directive to display its value when it changes. Surprisingly, it works fine in Firefox, showing the correct values. However, in other browsers like Chrome, it shows the op ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

Ways to remove the line under a logo in HTML using CSS and Bootstrap

While working on a website design, I encountered an issue with the logo where it has a line of the background color under it. This is frustrating and affects the overall design. Does anyone have a straightforward solution to remove this line? I need someth ...

Condition formulation using dynamic dust JS equality

I'm struggling with a seemingly simple task - dynamically changing the @eq condition. The example provided shows a default render, but what I really need is to allow user input to change it to either "Larry" or "Moe". You can view my code on jsfiddle ...