The class is failing to be applied to the parent div that holds an id starting with the letter x

I have been attempting to assign a class to the parent container when the child element has the 'hidden' class. If not, then a different class should be added.

function tagMissions() {
  if ($('span[id^="mission_participant_new"]').hasClass('hidden')) {
    $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
  } else {
    $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case');
  }
}

tagMissions();
<div id="mission_474453321" mission_id="474453321" mission_type_id="239" class="missionSideBarEntry" latitude="48.464928" longitude="11.929025" target_latitude="null" target_longitude="null">
  <!-- this is the parent div i am trying to assign the class to -->
  <div id="mission_panel_474453321" class="panel panel-default">
    <div id="mission_panel_heading_474453321" class="panel-heading">
        <a href="/missions/474453321" class="btn btn-default btn-xs lightbox-open" id="alarm_button_474453321"> Alarm</a>
        <span id="mission_participant_474453321" class="glyphicon glyphicon-user"></span>
        <!-- this is the span element with the id beginning with mission_participant_new_ -->
        <span id="mission_participant_new_474453321" class="glyphicon glyphicon-asterisk hidden"></span>
        <a href="" id="mission_caption_474453321" class="map_position_mover" target_latitude="null" target_longitude="null" data-latitude="48.464928" data-longitude="11.929025">Verkehrsunfall mit Linienbus</a></div>
    <div
      class="panel-body">
      <div class="row">
        <div class="col-xs-1"><img src="/Bus_rot.png?1484350177" id="mission_vehicle_state_474453321" class="mission_vehicle_state"></div>
        <div class="col-xs-11">
          <div id="mission_bar_outer_474453321" class="progress progress-striped mission_progress">
            <div id="mission_bar_474453321" class="progress-bar progress-bar-danger" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"></div>
          </div>
          <div id="mission_missing_474453321" class="alert alert-danger">Zusätzlich benötigte Fahrzeuge: 1 FwK</div>
          <ul id="mission_patients_474453321"></ul>
          <ul class="mission_prisoners" id="mission_prisoners_474453321"></ul>
        </div>
      </div>
  </div>
</div>
</div>

If a span element with an ID starting with mission_participant_new contains a class named hidden, it will add a class called lss_new_case_in_progress to the containing parent div whose ID starts with mission_panel. Otherwise, it adds the class lss_new_case.

This <div id="mission_XXXXX"> appears multiple times within the DOM structure. Can someone assist me in identifying the issue?

Answer №1

When you call tagMissions, make sure you are doing so within the context of a DOM element. If not, this will default to the window object, causing $(window).closest(...) to retrieve nothing.

It seems like your intention is to iterate over all elements with the naming convention mission_participant_new_XXX. To achieve this, you should use .each() for looping which will set this as the current iteration element.

function tagMissions() {
  $('span[id^="mission_participant_new"]').each(function() {
      if ($(this).hasClass('hidden')) {
        $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
      } else {
        $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case');
      }
    }
  });
}

tagMissions();
<div id="mission_474453321" mission_id="474453321" mission_type_id="239" class="missionSideBarEntry" latitude="48.464928" longitude="11.929025" target_latitude="null" target_longitude="null">
  <!-- this is the parent div i am trying to assign the class to -->
  <div id="mission_panel_474453321" class="panel panel-default">
    <div id="mission_panel_heading_474453321" class="panel-heading">
      <a href="/missions/474453321" class="btn btn-default btn-xs lightbox-open" id="alarm_button_474453321"> Alarm</a>
      <span id="mission_participant_474453321" class="glyphicon glyphicon-user"></span>
      <!-- this is the span element with the id beginning with mission_participant_new_ -->
      <span id="mission_participant_new_474453321" class="glyphicon glyphicon-asterisk hidden"></span>
      <a href="" id="mission_caption_474453321" class="map_position_mover" target_latitude="null" target_longitude="null" data-latitude="48.464928" data-longitude="11.929025">Verkehrsunfall mit Linienbus</a></div>
    <div class="panel-body">
      <div class="row">
        <div class="col-xs-1"><img src="/Bus_rot.png?1484350177" id="mission_vehicle_state_474453321" class="mission_vehicle_state"></div>
        <div class="col-xs-11">
          <div id="mission_bar_outer_474453321" class="progress progress-striped mission_progress">
            <div id="mission_bar_474453321" class="progress-bar progress-bar-danger" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"></div>
          </div>
          <div id="mission_missing_474453321" class="alert alert-danger">Zusätzlich benötigte Fahrzeuge: 1 FwK</div>
          <ul id="mission_patients_474453321"></ul>
          <ul class="mission_prisoners" id="mission_prisoners_474453321"></ul>
        </div>
      </div>
    </div>
  </div>
</div>

If you prefer not to loop, you can directly target elements using two selectors:

$('span[id^="mission_participant_new"].hidden').closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
$('span[id^="mission_participant_new"]:not(.hidden)').closest('div[id^="mission_panel"]').addClass('lss_new_case');

I suggest avoiding ID prefixes in selectors. Instead, assign a common class to elements with the same prefix, allowing you to simply use $('.mission_participant_new') for selection.

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

Tips for removing special characters from HTML?

I'm currently grappling with the concept of the filter My situation is as follows: $htmlData includes a user-entered html string formatted like this $htmlData = array('<em>test</em>', 'text here','\n') ...

Issue with JSON or Jquery: Uncaught error message: Cannot access property 'error' as it is null

I am attempting to initiate an ajax call using the jQuery code provided below. However, when I try this in Chrome, I encounter an error that says 'uncaught typeerror cannot read property 'error' of null'. This prevents the preloader fr ...

The Express app.post endpoint is not acknowledging incoming POST requests from Postman

I am facing an issue where my POST request using Postman to my express app is timing out. Here is the request: https://i.sstatic.net/UfL07.png And here is the app: import express from 'express' import bodyParser from 'body-parser' i ...

Trapped in the Web of Facebook OAuth

I've been struggling with this issue for a day now and I can't seem to pinpoint where I'm going wrong. I have experience working with JavaScript on the client side and recently started following a book tutorial. However, it appears that Face ...

Unable to retrieve Dictionary(Of String, String) using a GET ajax web request, but it functions properly with a POST request

This is the web method I have implemented: <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True, XmlSerializeString:=True)> _ Public Function GetDictionary() As Dictionary(Of String, String) ...

What process allows for this Twitter API response to be converted into HTML format automatically?

It is common knowledge that Twitter operates in an API-centric manner, meaning all Twitter apps retrieve their data through the API. Upon accessing (or .xml for those who prefer), a JSON formatted result with plaintext content and no additional formattin ...

JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it? function getResults(keywords) { foo.foo = function() { var bar = foo.getSomeText; // ...

Jquery failing to function properly when scrolling

I have been attempting to implement a feature where an element changes its position to fixed after scrolling past a certain point. However, no change occurs when I scroll. In the <head> section of my code, I have included <script src="stiler/jquer ...

What could be causing Prettier code formatter to suddenly stop formatting in VS Code?

I've been having trouble formatting my code using Prettier in VS Code. Even after reinstalling it, the issue persists and I can't seem to format my HTML/CSS code properly. The screenshot I provided shows that the code remains unformatted even aft ...

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

Maintain the fixed position of the table header while scrolling

I am facing an issue with my table setup - I want the header to stay fixed while scrolling through the body. Here is how my table structure looks: <table> <thead> <tr> <th>Header 1</th> ...

Enabling Multiple Login Feature in Node.js

const handleLogin = async (req, res) => { const User = require("../models/user"); const LoginInfo = require('../models/login_info'); try { const { email, mobile, password, otp } = req.body; const params = []; if(ema ...

Creating a unique directive specifically designed to be used within an ng

I have a unique custom directive that I implemented in AngularJS. The directive is called within an ng-repeat loop, as shown below: The array of objects, selectedMealCalc.calculated_foods, is aliased as 'items' <!-- CUSTOM DIRECTIVE --&g ...

There seems to be an issue with the bootstrap datepicker as it is throwing an error stating that $(

Currently in the process of developing a web application using AngularJS with MVC, I have integrated Bootstrap's datepicker into my project, Here is the code snippet: <div class="container"> <div class="row"> <div class=& ...

Using fancybox to send an ajax post request to an iframe

Can you send a variable to the iframe when using fancybox? This is my current setup: function fancyBoxLoad(element) { var elementToEdit = $("#" + $(element).attr("class")); var content = encodeURIComponent($(elementToEdit).oute ...

Different ways to create audio using GWT

Looking for ways to incorporate audio into your GWT app? I am considering creating a simple game, but it seems like there hasn't been much progress on direct audio support within GWT. This is likely due to the lack of underlying browser support, but I ...

There's just something really irritating me about that Facebook Timer feature

Have you ever noticed the timers constantly updating on Facebook? Whether it's an Ajax Request triggered by a timer or a client-side timer, there are numerous timers being used. Does this affect the performance of the website, and is there something c ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

AJAX Post data transmission on the network: Enhancing data formatting

For my AJAX post call, I need to format the data differently. The server is expecting the data in a specific format when viewed in Chrome Network Headers details. My task is to update the JavaScript code below to meet this formatting requirement: percenta ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...