Cease adding to the list once the condition is no longer valid

I am currently working on a project that requires me to clone span.response11, attach it to #parent, and then insert a new div into the cloned span.response11. I have successfully completed the cloning process, but I am facing an issue where my IF statement keeps adding the new div to elements that already have it appended.

For reference, here is a fiddle with my jQuery code: https://jsfiddle.net/4bmwbkgx/2/

// if this cloned element doesn't already have the child div.red, append it.
$("#parent > span").each(function(index, element) {
  if ($(element).not(":has(.red)")) {
    $(element).prepend('<div class="red">This is red</div>');
  }
});

I want the div.red to be added only once. If span.response already contains div.red as a child, the jQuery script should not add any more divs.

How can I modify my function to prevent additional divs from being added?

Answer №1

In the scenario where span.response already contains div.red as a child, jQuery should refrain from adding additional div's.

Avoid using :has; it is designed for testing the same element. Instead, utilize .find to verify its existence:

$("#parent > span").each(function(index, element) {
  // Only execute the following code if `.red` does not exist within this element.
  if (!$(element).find(".red").length) {
    $(element).prepend('<div class="red">This is red</div>');
  }
});

In addition, I strongly advise against inserting <div> inside <span>, given that <span> is an inline element while <div> is block-level!

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

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

The FireBase dispatch functionality fails to update the real-time database

Struggling with a realtimeDB issue while using NuxtJS to manage state and send it to the DB. Saving data works fine, but editing results in a 400 BAD Request error. This error also occurs when trying to manually update information within Firebase realtime ...

arrange data based on table heading using vue.js

I've recently upgraded to Vue 2.x and found out that the orderby directive is no longer supported as per this documentation. I'm trying to avoid adding another JavaScript library, but if using lodash is the only option, I'm willing to give ...

Show an item vertically centered within its parent container

Following is the appearance of the selector: https://i.sstatic.net/njql9.png The text currently appears close to the bottom of the selector. I would like it to be centered vertically while maintaining its horizontal positioning towards the left side. He ...

Reading and writing to a file in a UI automation using JavaScript: Tips and tricks

While running, I need to identify several properties and create a json object that I want to write to a ".json" file and save on disk. var target = UIATarget.localTarget(); var properties = new Object(); var jsonObjectToRecord = {"properties":properties} ...

Node.js VAR DeclarationIn the world of Node.js, we make

I am currently expanding my knowledge on Node.js. I came across a line in my book that has sparked my curiosity, and I wanted to seek some clarification. The specific line in question is: var user = req.user = users[req.params.name]; After doing some re ...

Working with Vue.js: Binding to dynamically generated form elements

I am facing an issue where form elements are not available in the html document until an inline script runs on page load. In Vue.js, how can I bind to these form elements after the page loads? While with jQuery I could use a $('.element').each(), ...

The nested click event is not functioning as expected

Below is a simplified version of HTML code containing 2 nested click events (one on the href and one on an input). When the user clicks on the input field, it inadvertently triggers the javascript function SelectTable() linked to the href event. This unint ...

How to implement Google Tag Manager using the next/script component in Next.js 11?

Version 11 of Next.js recently introduced a new approach with the Script component offering various strategies. To avoid duplicate tags, it is advised to implement Google TagManager using the afterInteractive strategy. In my experimentation: // _app.js ...

Failure to apply CSS to the class element instead of the div tag

Looking to update the CSS code below to change the color of a div to blue when it matches a specific class: I attempted the following changes, but they did not produce the desired result: &__header { display: flex; justify-content: space-betw ...

guide on utilizing nested loops and arrays in Vue.js

The results returned by the controller query are as follows: date: {2020-09-24: {work_hours: 7}, 2020-09-30: {work_hours: 8}} 2020-09-24: {work_hours: 7} 2020-09-30: {work_hours: 8} Within my Vue component, I am attempting to use ne ...

Is it possible to use jQuery for drag-and-drop functionality?

Currently, I am working on developing a drag-and-drop widget that consists of 3 questions and corresponding answers. The user should only be able to fill in 2 answers in any order, while the third drop area should be disabled. This third drop area can be l ...

When a number is added to an array containing strings, the result is a string rather than a number

Currently, I am attempting to change my array key value from a string to a number within my JSON object: form["price"] == "23" console.log(typeof form["price"]) // string form["price"] == Number(parseFloat(this.formObject[field.fieldName])) The issue aris ...

Turn off cursor:pointer for disabled checkbox labels

Is there a way to apply the cursor:pointer style to checkboxes and their labels, but only for those that are not disabled? This is the code snippet I am currently using: <label> <input type="checkbox" ...more attributes... ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

Transform a dropdown menu into an inverted footer

I stumbled upon a unique dropdown menu design that I want to tweak and reverse, making it an innovative "dropup" menu that opens from the bottom to the top. Currently, this is what I have: HTML <div class="get-started"> <a href="#" id="get-s ...

Incorporate my personal design flair when utilizing third-party React.js component libraries

Incorporating Material UI as a component library in my React project has been beneficial. However, I am facing a challenge where the inline styling provided by Material UI clashes with my existing custom styles that I have developed over time. Is there a ...

How to Center a Button in a Menu Using CSS

I've been struggling for a while now trying to design a menu with standard buttons on the left and a single button on the right. I've experimented with various techniques using ul li and applying styles like float, but nothing seems to work! No m ...

Transforming content dynamically

I am currently working on a single-page website that features a comprehensive product catalog. Here are the key elements I'm focusing on: A one-page website layout, complete with header, content, and footer (developed using HTML5/CSS3) Dynamic cont ...

Having trouble retrieving exchange rates from the state in React after making an API call

import React, { Component } from 'react'; import axios from 'axios'; class SearchCurrency extends Component { constructor() { super(); this.state = { data: {} } } componentDidMount() { axios .get(&apo ...