What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with:

<%
    while(resultSet1.next()){
                        out.println("<p class='comm'>");
                        out.println(resultSet1.getString("answer_content"));
                        out.println("</p>");

                    }
%>

Next, here is the script that I implemented:

<script>

            $( document ).ready(function() {

                var par = document.getElementsByClassName("comm");

                var insert = document.createElement("form");
                insert.setAttribute("action","ForumSubmitCommentController");

                var text = document.createElement("input");
                text.setAttribute("type","text");
                text.setAttribute("name","comm_text");
                text.setAttribute("id","comm_text");
                insert.appendChild(text);

                var comm_submit = document.createElement("input");
                comm_submit.setAttribute("type","submit");
                comm_submit.setAttribute("value","Comment");
                insert.appendChild(comm_submit);

                par.appendChild(insert);

           });

        </script>

Despite my expectations of having a form attached to all 'p' elements with "class='comm'," it appears that no forms are being added. Can someone please assist me in identifying where I may have gone wrong? Thank you in advance.

Answer №1

because par is an array, it does not have the appendChild method

$(document).ready(function () {
    $('.comm').each(function () {
        var insert = document.createElement("form");
        insert.setAttribute("action", "ForumSubmitCommentController");

        var text = document.createElement("input");
        text.setAttribute("type", "text");
        text.setAttribute("name", "comm_text");
        text.setAttribute("id", "comm_text");
        insert.appendChild(text);

        var comm_submit = document.createElement("input");
        comm_submit.setAttribute("type", "submit");
        comm_submit.setAttribute("value", "Comment");
        insert.appendChild(comm_submit);

        this.appendChild(insert);

    })
});

Demo: Fiddle


However, a simpler way to achieve this is by using

$(document).ready(function () {
    var form = '<form action="ForumSubmitCommentController"><input type="text" name="comm_text" id="comm_text"><input type="submit" value="Comment"></form>';

    $('.comm').append(form)
});

Demo: Fiddle

Answer №2

Performing DOM manipulations like this is typically straightforward when using a library such as jQuery, but it can become difficult or verbose when working with the plain old DOM API.

For instance, document.getElementsByClassName retrieves an HTMLCollection, which is an array-like collection of elements. To apply changes to all of these elements, you must iterate through them and apply the necessary modifications.

Here's an example:

nodesList = document.getElementsByClassName("helloworld");
for(var i = 0; i < nodeList.length; i++) {
    var node = nodeList[i];
    // create form etc...
    node.appendChild(form);
}

It's worth noting that the HTMLCollection does not have a forEach method, so you need to either use a standard for-loop or convert it into an array first (such as by utilizing methods like this one). Additionally, before each call to appendChild, you must create a new form node (or utilize cloneNode) because each DOM node is unique and appendChild simply relocates it within the DOM structure.

Libraries like jQuery handle these details under the hood, abstracting away complexities and enhancing code readability. While understanding the DOM API is valuable, in practical projects, relying on jQuery for all manipulation tasks is often more efficient and manageable. Focus on mastering jQuery and leverage its capabilities for your development needs.

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

Using Symfony2 to make an Ajax request in order to show a message based on a particular condition

As a novice in the realm of JavaScript and Ajax, I am struggling to find a way to display a message based on certain conditions. Let's consider a scenario where a user can adjust the quantity of a product they wish to purchase. While implementing thi ...

Extension for Chrome that enhances YouTube video playback experience

I'm struggling to figure out why this isn't functioning. I've reviewed the Google extension dev docs and examined some sample code. Checked various Stack Overflow questions and answers, but haven't received any helpful feedback or res ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

What could be the reason behind the disruption in this JavaScript associative array?

I'm facing an issue with my associative array, which I have confirmed through console.log to be initially: this.RegionsChecked = {"US":true,"APAC":true,"Canada":true,"France":true,"Germany":true,"India":true,"Japan":true,"LATAM":true,"MEA":true,"UK": ...

Updating the values of parent components in Vue.js 3 has been discovered to not function properly with composite API

Here is a Vue component I have created using PrimeVue: <template lang="pug"> Dialog(:visible="dShow" :modal="true" :draggable="false" header="My Dialog" :style="{ width: '50vw' }" ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

Ways to slow down page transition on NextJs

I'm currently working on securing my private pages using a HOC withAuth. While the protection is functioning correctly, I am looking to avoid users seeing a loading screen for a split second while the access token is being retrieved from local storage ...

I have been experiencing issues with browserify when trying to use both jquery and jquery-ui

I have created a simple test app to showcase an issue I am facing. You can find the demo on this GitHub repository. In this demonstration, the first step was installing jquery and jquery-ui: npm install --save jquery jquery-ui Then I proceeded to creat ...

SVGs do not display on iPhones

Having some issues with my code - specifically, I have an SVG animation that seems to work on all devices except iPhones. I've been struggling to find a solution. Here is the code snippet for the SVG: <div class="contenuto-svg"> <svg vi ...

Is it possible to slide-toggle and alter the background color of a div when clicked?

Imagine having several div's on a webpage all with the ID of "Toggle". Each div contains two other smaller divs. "Headline" which is always visible. "Comment" which appears/disappears when the headline is clicked (initially hidden). How could I ac ...

Displaying random divs and subsequently animating them downwards using JavaScript

I am in the process of creating a random appearing div that then falls down. Here is the code I have so far: $(document).ready(function(){ $('#test').animate({top: 80 + '%'},900); }); <div id="test" style="background:#98bf21;heigh ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

Is there a way to arrange an HTML list in this specific manner using CSS or JavaScript?

I need to arrange a list of items in columns with 5 rows each, as shown in the attached image. This list is generated dynamically using an SQL query with a loop on the li tag. I am looking for a solution to order the list in this way using javascript or ...

In the XHTML mode, MathOverflow's invaluable mathematical expertise shines brightly

I am interested in incorporating the unique “piece of valuable flair™” from MathOverflow onto my website. The issue I am facing is that I want my webpage to comply with XHTML5 standards, meaning it should be served with the MIME type application/xht ...

Show a div depending on user input

For those with more programming experience than myself, I have a simple question. In Rails, using coffescript, I want to show additional content based on a user's selection. Essentially, if they click on a checkbox, it should reveal an extra field for ...

What is the best way to determine which watchers are triggered in Vue.js?

Within my parent component, there are numerous nested child components. Whenever a click occurs on one of the child components, it triggers an update to the route. The parent component watches the route property and performs certain actions when it change ...

Having trouble retrieving the value of the second dropdown in a servlet through request.getParameter

I am facing an issue with storing the value of the second dropdown in a servlet after utilizing an ajax call in Java to populate it based on the selection made in the first dropdown. While I was able to successfully store the value of the first dropdown ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

AJAX form in a partial view displaying a summary of validations

I am facing an issue with my application that utilizes an AJAX form. Whenever the form is submitted and fails validation, I return the partial view in which the form resides. In this scenario, I would expect the Validation Summary to be displayed. However, ...

I am experiencing difficulties in accessing the DOM

I have implemented jQuery $.ajax to dynamically load data into table rows as shown below: <table id='row-data'> <tr><td>1001</td></tr> <tr><td>1322</td></tr> <tr><td>15 ...