Insert HTML elements into nested CSS classes

My goal is to utilize jQuery for looping through classes and adding text to an HTML element. I am currently working with the following example HTML:

<div class="question">
    <div class="title">
        <strong>Here's the question title.</strong>
    </div>
    <div class="choice">Here's choice1.</div>
    <div class="choice">Here's choice2.</div>
</div>
<div class="question">
    <div class="title">
        <strong>Here's the question title.</strong>
    </div>
    <div class="choice">Here's choice1.</div>
    <div class="choice">Here's choice2.</div>
</div>

I am trying to loop through each question on the page, check if the title matches a specific string, and then append some text accordingly. Here is my current code snippet:

$('.question').each(function() {

    var title = $(this).find('.title').text();

    $('.choice').each(function() {

        var span = document.createElement("span");

        if (title == "someString")
        {
            span.className = "someClass";
        }
        else
        {
            span.className = "someOtherClass";
        }

        var text = document.createTextNode("text");
        span.appendChild(text);

        $(this).append(span);
    });

    document.body.style.backgroundColor = "orange"; // to test the outer loop
});

The text should change color based on the title, hence the different CSS classes. However, nothing seems to be happening - the text is not being appended to each choice. The background color does change to orange, and there are no errors in Chrome developer tools. Any assistance would be greatly appreciated.

Answer №1

To retrieve the title, you can follow this method:

var title = $(this).find('.title strong').text();

You seem to be mixing up jQuery with vanilla JavaScript here. Since $(this) is a jQuery object, you cannot utilize appendChild(). Here's how you can correct that:

$(this).get(0).appendChild(span);

Alternatively, you have the option to directly use jQuery like so:

$(this).append(span);

Answer №2

After working with Arun P Johny's fiddle, I have made some updates;

FIDDLE

Here are the key modifications;

var title = $.trim($(this).find('.title').text());

    $(this).find('.choice').each(function () {...

I switched $('.choice') to $(this).find('.choice') so that only the elements within that question are affected, not all choice elements on the page.

also changed find('.title').innerHTML; to find('.title').text()); to specifically target the text inside that div, excluding the html content.

Answer №3

Is this what you're looking for?:

Jsfiddle

Implementing jQuery code with comments removed:

// Executes when the document is ready...
$(function () {

    // Target each title element...
    $('.title').each(function () {

            // References each title element as defined above
        var title = $(this),
            // Retrieves all siblings of title element(s)
            choices = title.siblings(),
            // Ternary operator. Essentially an if-else statement
            myClass = title.text().trim() === "Here's the question title." ? "someClass" : "someOtherClass";

        // Create a span element...
        $('<span />', {
            class: myClass,         // Assign it a class
            text: " Appended text"  // Add some text to it
        }).appendTo(choices);       // Append the span to every .choice element

    });

});

HTML structure:

<div class="question">
    <div class="title"><strong>Here's the question title.</strong></div>
    <div class="choice">Here's choice1.</div>
    <div class="choice">Here's choice2.</div>
</div>

<div class="question">
    <div class="title"><strong>Here's the question title.</strong></div>
    <div class="choice">Here's choice1.</div>
    <div class="choice">Here's choice2.</div>
</div>

<div class="question">
    <div class="title"><strong>Here's title.</strong></div>
    <div class="choice">Here's choice1.</div>
    <div class="choice">Here's choice2.</div>
</div>

CSS styling:

.someClass {
    color: red;
}
.someOtherClass {
    color: green;
}

.question { margin: 10px 0px; }

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

How to use getBoundingClientRect in React Odometer with React Visibility Sensor?

I need help troubleshooting an error I'm encountering while trying to implement react-odometer js with react-visibility-sensor in next js. Can anyone provide guidance on how to resolve this issue? Here is the code snippet causing the problem: https:/ ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Instructions for uploading a file in a JSP form without triggering the submit button function

I am struggling with implementing file upload functionality into my JSP form page without having to submit the form. I have tried various methods, including AJAX calls, but nothing seems to work as expected. On my JSP page, the upload field displays based ...

Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but enco ...

Integrate an input field with a copy function similar to the GitHub clone view

Can anyone help me create a view with a tooltip similar to the one on Github? You can see the example here: I attempted to use CSS but couldn't quite replicate the exact UI. Here is my current CSS code: [tooltip] { display: inline; position: rel ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

The header element in JSP is concealed prior to the page being fully loaded

I have a basic login page titled login.jsp that includes header and footer content. The header content is stored in pageheader.jsp which consists of the header body tag, etc. I am looking to hide the header and footer elements specifically on the login pa ...

Remove all of the classes from the specified element using JavaScript

I have a button and I want to remove all the classes when it is clicked. Here is what I have tried: button.style.className = '' document.querySelector('button').onclick = function() { this.style.className = ''; } .myClas ...

Easy ways to align sprite images and text in the center

I am trying to utilize css sprites for my website. I have a basic image and some text that I would like to display together. My goal is to center the image on the page, and then vertically center the text next to it. As a newcomer to css, I am struggling t ...

Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route ch ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

I am struggling to understand the significance of the $ symbol in this particular context

I came across the following snippet in a book I've been reading: `images/${Date.now()}.jpg` The curly brackets used here signify 'out of string', but I'm unsure about the meaning of $... P.S. Honestly, I didn't want to ask a que ...

Issue encountered: Document not being saved by Mongoose, error message received: "MongoClient connection must be established"

Currently, I am attempting to establish a connection with MongoDb using mongoose. Below is the code snippet that I have implemented for this purpose: controller.js const conn = mongoose.createConnection(db, { useNewUrlParser: true, ...

Tips for successfully including a forward slash in a URL query string

My query involves passing a URL in the following format: URL = canada/ontario/shop6 However, when I access this parameter from the query string, it only displays "canada" and discards the rest of the data after the first forward slash. Is there a way to ...

Show or hide a div in Vuejs based on checkbox selection

I've been attempting to toggle the visibility of a container div using Vuejs with no success. I've tried two different methods, but neither seem to work for me. Here is Method 1: <body> <div class="checkbox" id = "selector"& ...

Navigate files on a Windows server remotely using a Linux Apache web server by clicking on a browser link

After setting up an apache webserver on Linux Debian and successfully creating an intranet, I encountered a challenge. The intranet is designed to display tables with data from sql queries using php and mysql. However, I wanted to include a hyperlink withi ...

"Receiving the error message 'Object is not a function' occurs when attempting to pass a Node.js HTTP server object to Socket.IO

A few months back, everything was working fine when I set up an HTTPS server. Recently, I revisited the application and decided to switch to HTTP (though this change may not be directly related). In my code snippet below from 'init.js', I create ...

Bottom section goes haywire in Chrome when clearfix is applied to a div above

When I remove the clearfix div above the footer, the text aligns correctly on Firefox. However, this causes issues with other elements on the page. It's puzzling how the clearfix is impacting the footer in this way... Here is a link to my page: ...

Retrieve data from JSON using AJAX

I am working with an API that provides JSON data in the following format: [{ "Code": "001", "Name": "xyz", "Members": [{ "FullName": "User1" }] }, { "Code": "002", "Name": "asd", "Members": [{ "FullName": "User2 ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...