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

Troubles with NextJS and TailwindCSS Styling

I encountered a strange issue when I used the component separately. Here's how the code looked like: <> <Head> <title>Staycation | Home</title> <meta name="viewport" content="initial- ...

Event response lacks necessary latlng data from Gmaps API

Currently, I am utilizing Angular UI Google Maps and facing an issue in retrieving the latlng when a map click event occurs. Although the map is responding, it is not providing the latlng information as expected. Below is the excerpt of my code: Controlle ...

Transform yaml strings into JSON entities

We are facing a challenge with two separate codebases that have different localization styles. One codebase uses yaml, while the other uses JSON. Currently, we are working on transitioning to the JSON-based codebase. However, with 20k yaml strings and sup ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

Performing a deep insert in SAPUI5 with the Kapsel Offline App on an OData V2 Model

Query: What is the process for performing a "Deep Insert" from a SAPUI5 Client application on an OData V2 Model? Situation: In my SAPUI5 Client application, I need to Deep Insert an "Operation" along with some "Components" into my OData V2 Model. // h ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

How can I resolve the issue with the HTML/CSS footer not functioning properly on Safari for iPhone in my mobile site?

Struggling with a mobile website issue here. The client wants text-based buttons/links at the bottom, so I added them in, but my skills with size percentages are a bit rusty. I need these buttons to line up horizontally and adjust their width accordingly ...

Add AngularJS to an AJAX call when the user clicks on it

I'm currently exploring the SoundCloud API and looking to implement a feature where users can add a song to the page by clicking on it from the search results. I've decided to utilize Plangular, which you can find more information about here. How ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

Selecting a Child Component in Vue.js: A Guide to Specifying the Correct Component

Within my application, I have a variety of components that are either generic or specific to certain brands. For example, I have two brand-specific components named Product_brand_A.vue and Product_brand_B.vue, both of which I want to display in a list form ...

Navigating to a Different Page in React Based on Button Click and Meeting Specific Conditions

Within this particular component, I have implemented a button named Submit. When this button is clicked, it triggers a series of actions: first, it exports the drawing created by the user as a jpeg URL, then sends this image data to another API that genera ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Retrieve the content of a specific HTML tag using JavaScript

Is it possible to extract the content of a specific HTML tag as a string or XML format? <body> <script src="jquery.min.js"> //var test = document.getElementsByTagName("input"); //alert(test[0]); $(document).ready(function ( ...

Utilizing the JSON.parse method in JavaScript in conjunction with an Ajax request while incorporating the escape character "\n" for new line functionality

https://jsbin.com/zuhatujoqo/1/edit?js,console Edit: json file has this line: {"pd":"ciao \\n ste"} I need to retrieve a valid JSON file through an ajax call. Then parse the result using JSON.parse. I'm confused about the behavior of t ...

"Troubleshooting: Inability to send emails through PHP mail script while using jQuery's

I'm at a loss with this issue. I'm attempting to utilize the jQuery ajax function to send POST data to an email script. Below is the jQuery code snippet. $('#bas-submit-button').click(function () { var baslogo = $('input#bas- ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

How to Create a Floating DIV with CSS

Here is the URL I am referring to: Website I want to position the Weather DIV above other content on the page while still maintaining its position when expanded or collapsed. How can I achieve this without affecting the layout of other elements? This is ...

Developing a dynamic master-details view on a single page with ASP.NET MVC

This is a question related to design and technology. When using ASP.NET MVC, it is possible to create a simple application with two views: one master view that displays all records in tabular form in read-only mode, and another details view for creating n ...

Implementing dynamic active class changes in a navbar with JavaScript

My goal was to have the navbar change its class to 'active' dynamically when a user clicks on the <li> tag. Can you help me pinpoint where I made a mistake? dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a'). ...