Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute:

<p class="form-row form-row-wide" data-child-field="child_has_jacket">
</p>

Even after trying with jQuery :

jQuery(document).ready(function( $ ){
       $('.form-row [data-child-field='child_has_jacket']').addClass("selected");
  });

Unfortunately, it doesn't seem to be working as expected. Any suggestions?

Answer №1

you are encountering a syntax error. Simply replace the ' with " in the data attribute class selector

data-child-field="child_has_jacket"
. Also, make sure there is no space between the attribute selector and the class, as it will result in searching for a child element with the data attribute.

The correct format should be:

$('.form-row[data-child-field="child_has_jacket"]')

Check out the snippet below:

jQuery(document).ready(function( $ ){
       $('.form-row[data-child-field="child_has_jacket"]').addClass("selected").html("selected class added");
  });
.form-row.selected {
  border:1px solid black;
  display:block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="form-row form-row-wide" data-child-field="child_has_jacket">
</p>

Answer №2

  1. To ensure proper functioning, use the code

    $('.form-row[data-child-field=child_has_jacket]').addClass("selected");
    . It is important to remove any spaces after .form-row to avoid searching for a child element based on that data attribute.

  2. Don't forget to include ; in CSS when defining properties like height and display.

Here is a working snippet:

jQuery(document).ready(function( $ ){
   $('.form-row[data-child-field=child_has_jacket]').addClass("selected");
});

/*Other working snippets
jQuery(document).ready(function( $ ){
   $('.form-row[data-child-field="child_has_jacket"]').addClass("selected");
});

jQuery(document).ready(function( $ ){
   $(".form-row[data-child-field='child_has_jacket']").addClass("selected");
});*/
.form-row.selected {
  border:1px solid black;
  width:20px;
  height:20px;
  display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="form-row form-row-wide" data-child-field="child_has_jacket">
</p>

Additional working examples:

jQuery(document).ready(function( $ ){
   $('.form-row[data-child-field="child_has_jacket"]').addClass("selected");
});

jQuery(document).ready(function( $ ){
   $(".form-row[data-child-field='child_has_jacket']").addClass("selected");
});

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 there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...

Creating a loading screen in Angular 4: Insert an item into the HTML and then set it to disappear automatically after

I'm dealing with a loading screen that typically takes between 15-30 seconds to load about 50 items onto the page. The loading process displays each item on the page using the message: Loading item x For each data call made to the database, an obser ...

Enhance Your List with Icon Decorations

Is it feasible to utilize a sprite image in place of the default bullet for an ul list? Is this achievable? ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Changing a complex array structure in javascript into a CSV format

I have a complex nested array that I need to convert into a downloadable CSV file. My current approach involves iterating through each array and subarray to build the CSV, but I'm wondering if there's a more efficient method available? Here is a ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

Alter the classification of the tag

I am trying to modify the class of a tag upon clicking it. For reference, here is the jsFiddle link: http://jsfiddle.net/9u8Nc/ This is the HTML code I have: <ul class="tags"> <li> <a href="javascript:void(0)" class="tag">Adventure&l ...

What is the process for appending a value to an array of JSON objects?

I have a JSON array containing objects which I need to pass the values to the DataTables. [{ _id: '58a2b5941a9dfe3537aad540', Country: 'India', State: 'Andhra Pradesh', District: 'Guntur', Division: ...

What methods can be used to determine if a webm file contains audio or video content?

In the process of creating an uploader using ReactJS, I encounter an issue related to identifying whether uploaded files are video or audio. Specifically, when users upload audio files with a .webm extension (e.g., music.webm) and the MIME type is set as & ...

Angular checkbox filtering for tables

I have a table populated with data that I want to filter using checkboxes. Below is the HTML code for this component: <div><mat-checkbox [(ngModel)]="pending">Pending</mat-checkbox></div> <div><mat-checkbox [(ngModel ...

Tips for saving HTML code within a concealed field utilizing jQuery

What is the best way to store a string with HTML tags in a hidden field using jQuery? I am attempting to use this code, but it's not functioning as expected: var terms = $('#TermsAndCondition').val(); alert($('#hdnTerms').val( ...

Karma is unable to locate the module within the specified relative path

I'm facing a challenge with Karma not being able to load a specific file. As a novice in Karma, I dedicated the entire day to researching and checking documentation for similar issues with no luck. Upon initiating the karma process, it encounters an ...

"What is the best way to eliminate duplicate data from an ng-repeat loop in AngularJS

I have a query regarding appending data from the second table into $scope.notiData in AngularJS. Additionally, I need to figure out how to remove ng-repeat data when the user clicks on the remove symbol X. I have attempted some code but it is not functioni ...

I noticed a significant space below the footer on my webpage. As a first-time website creator, are there any solutions to this

I'm currently in the process of working on my very first website for a study project using HTML and CSS. There's an issue where there is a large gap below the footer that I can't seem to eliminate. I've only completed 3 pages so far, bu ...

Troubleshooting problems with hosting create-react-app on IIS and Internet Explorer

Having some trouble setting up my React application that was built using the React Create App template. When trying to host it with IIS, I encountered some issues. The index.html main page seems to be loading fine, but the compiled JS file is not loading ...

Exploring jQuery Efficiency: Comparing CSS and Animation Techniques

I am trying to steer clear of using the animation property because it tends to be slower compared to CSS3 animations. My query is whether utilizing the css method is faster than the animation property, but still slower than a direct CSS3 animation with tr ...

The compatibility issue between jQuery Tabs and Sliding effect

Hey there, I'm currently working on a website that requires a vertical tab system. I also have an arrow image that shows which tab or thumbnail the user has selected, and it should smoothly slide between the two thumbnails. You can check out the pro ...

How One Simple Click Can Impact Every Button in jQuery Ajax操作

Whenever I try to click a button that should only affect a specific id, it ends up affecting every button on the page by sending data to our API as well. You can check out a snapshot of my page here. Each row has a unique id, but when I click the vote butt ...

Is data shared globally for each HTTP/Session request?

QUERY: Is there a method to establish a variable storage specific to each session or HTTP request? The variable should be accessible globally within that session/request/connection, without the need to pass it between functions. For instance (as an examp ...

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...