Filtering by labels

I need to search for the label "1125" and if it is not found, I want to show an alert box. Here is my code:

if (var id = $('mobilelabel_2:contains("1125")').attr('for');)
{
    alert ("works");
}
else
{
    alert ("try again");
}

Answer №1

In order to target an element with specific ID or class, you need to use either . or # character:

  if ($('#mobilelabel_2:contains("1125")').length > 0)
  {
      alert ("works");
  }else{
      alert ("try again");
  }

HTML

<label id="mobilelabel_2">Test 1125</label>

It's worth noting the updated syntax for the if statement. You don't have to fetch the value of the for attribute and save it in a variable. Instead, you can simply check the length of the element that includes the text 1125.

JS Fiddle: http://jsfiddle.net/8R98b/

Answer №2

Hey there! Here's a helpful tip: Before sharing your code here, it's always a good idea to run it through either jshint or jslint.

After running your code through jshint, it looks like there are 11 warnings:

1   Expected an identifier but found 'var'.
1   Expected ')' to match '(' from line 1 but found 'id'.
1   Expected an identifier but found '='.
1   Expected an assignment or function call but found an expression.
1   Missing semicolon.
1   Expected an identifier but found ')'.
1   Expected an assignment or function call but found an expression.
1   Missing semicolon.
5   Expected an identifier but found 'else'.
5   Expected an assignment or function call but found an expression.
5   Missing semicolon.

It seems like you might be attempting to write this instead:

if ($('#mobilelabel_2:contains("1125")').length > 0)//ele with id mobilelabel_2 contains text 1125
{
    alert ("works");
}
else
{
    alert ("try again");
}

Answer №3

Your code has been corrected with the use of JQuery, right..?

if (var id = $("#mobilelabel_2:contains('1125')").attr('for')
{
    alert ("it's functioning");
}
else
{
    alert ("give it another shot");
}

Thumbs up! 👍

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

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

Is there a way to retrieve the precise floating-point width of an element?

When attempting to determine the precise width of a table cell, I encountered some discrepancies. While IE9's developer toolbar indicated a width of 203.68px in the Layout tab, using element.clientWidth and other methods yielded a rounded integer valu ...

Having images that are too large in size and using a high percentage can

I'm encountering a strange issue. When I define the width and height of my images in pixels in my CSS file, all my jQuery animations and events work perfectly fine. However, when I switch to using percentages or 'auto' for the image dimensio ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...

Issue encountered while attempting to log out a user using Keycloak in a React JS application

I'm currently working on implementing authentication for a React JS app using Keycloak. To manage the global states, specifically keycloackValue and authenticated in KeycloackContext, I have opted to use React Context. Specific Cases: Upon initial r ...

Tips for retrieving the most recent UI updates after the container has been modified without the need to refresh the browser

Currently, I have developed a micro frontend application in Angular using module federation. This application is hosted in production with Docker containers. My main concern revolves around how to update the UI changes for the user without them needing to ...

Adding schemas to the router of a Next.js 13 app is a helpful feature that can

Summary: In Next.js 13, the /app router's new changes to layout and page routing have altered how we add content to the <head>. The challenge now is how to include a schema script on each page. Next.js automatically combines <head> tags f ...

How can one determine the completion of a chunked download request in Angular's HTTP client?

Currently, I am utilizing angular's HttpClient to retrieve an arraybuffer. The server is transmitting the data along with the following headers: *To avoid any confusion, the download route essentially retrieves a chunk file stored in the cloud. Howev ...

Updating Element Value in Python Using JS and Selenium

Hello, everyone. I'm new to coding and seeking some help regarding a problem I encountered with using 2captcha for my Python web scraping automation. Upon running the script, I receive the captcha token from 2captcha as instructed in their API documen ...

The hover state of a div will not be lost if its parent element is not being hovered over

When hovering over the second, third, or fourth item, hidden text will appear on the left side. If you hover your cursor over the hidden text, it will disappear again. I want to be able to hover over the second item, move my cursor to "hide", and click o ...

What is the process of generating a popup panel without relying on libraries, using JavaScript and CSS?

I'm currently working on creating a popup panel that is centered on the screen with rounded corners (scrollbars are unnecessary) using jQuery min, similar to this example: https://i.stack.imgur.com/0kYO6.png My progress so far: function (package) ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

Opening a window in ExtJS when another window is already open

It seems like I'm having trouble opening a new window on top of another window that is already open in ExtJS 6. I have tried setting the model to true and bringToFront to true, but unfortunately, neither of them is working as expected. https://i.sstat ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

Tips on retrieving complete information from mongoose when the schema contains a reference

I have a schema that includes [content, name, email], and I need to retrieve all three data fields and render them on the frontend simultaneously. Can you provide an example of JavaScript code that accomplishes this? const UserSchema = new mongoose.Schem ...

Is TypeScript's nullish coalescing operator (??) supported by more browsers compared to JavaScript's equivalent?

When it comes to the nullish coalescing operator (??) in JavaScript, browser support is limited to newer browsers such as Chrome 80, Edge 80, and Firefox 72. Since TypeScript gets converted to JavaScript, do nullish coalescing operators also undergo some ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

The console displays "undefined" when formatting API data

I am attempting to format the data retrieved from an API since there is a lot of unnecessary information. However, when I try to display the formatted data in the console, it always shows as "undefined" or "null." I am importing and calling the fetch API ...