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

Designing a structure with three fieldset components

I'm currently trying to design a page layout that includes three fieldsets. My goal is to have the first one span across 100% of the width, with the other two positioned side by side below it at 50% width each. However, I am struggling to achieve thi ...

Executing functions from main component in tanstack table operations

One of the reusable React components I have is: "use client"; import { useState } from "react"; import { ColumnDef, flexRender, ColumnFiltersState, getFilteredRowModel, getCoreRowModel, getPaginationRowModel, ...

What are the steps to launching a yarn app on a dev server?

I've always stuck with npm and never ventured into using yarn or webpack explicitly. The code from this repository needs to be executed: https://github.com/looker-open-source/custom_visualizations_v2 I'm looking for a way to run it like a develo ...

Using the .slider class on concealed div elements

Explaining this may be a bit tricky, but here we go... I have multiple hidden divs that switch with each other when a link is clicked using $(document).ready(function(){ $('a').click(function () { var divname= this.name; $("#"+divname ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

a method for inserting a space after a certain character, with the exception of when that character is located at the start or end of a line

I've created a regular expression that can modify various patterns like: anything1 * anything2* anything3 anything1* anything2 * anything3 anything1 * anything2 * anything3 anything1*anything2 *anything3 anything1 * anything2 *anything3 anything1*any ...

Tips for altering the browser tab color on a PC or Mac with HTML or JavaScript

While I am aware of the method to change theme colors on mobile devices using <meta name="theme-color" content=" #0000ffbb" />, I prefer browsing on my laptop. Are there ways to customize browser tab appearance using HTML or JS fo ...

Calling Node Express request inside a GET route

I am currently utilizing nodejs as an intermediary layer between my public website and an internal server within our network. Through the use of express.js, I have created a basic REST api where the endpoint should trigger a request call to a webservice a ...

Durable Container for input and select fields

I need a solution for creating persistent placeholders in input and select boxes. For instance, <input type="text" placeholder="Enter First Name:" /> When the user focuses on the input box and enters their name, let's say "John", I want the pl ...

"During a single click event, the jQuery AJAX function is invoked a total of 6

For my project using C# MVC 5, I have implemented an AJAX call on the client side with the following code snippet: function addEventListener() { $('#createNotification').bind('click', function (e) { if($('# ...

What is the best way to ensure that these social icons are perfectly centered on the page across all web browsers?

Visit my website here: foxweb.marist.edu/users/kf79g/contact.php I'm stuck on the final step needed to deploy my website and finish it. The issue I'm facing is with the social icons when viewed on medium and small screens. I want them to be cent ...

I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data: export default new Vuex.Store({ state: { user_data: util.fetch_user_data('username') ... } located in the util.js file: util. ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...

AngularJS is experiencing issues with the sorting filter 'orderBy'

I am experiencing an issue with sorting a table list that has three columns. I have implemented the ability to sort all columns in ascending and descending order. However, when I click on the -Tag to initiate the sorting process, I encounter the following ...

Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks? For example, if we have a function called 'access' that is registered to invoke a Java function: access(function(blabla){ ... }); Are there eff ...

Unable to activate check box button by clicking on it

Hi there! I am having trouble with a checkbox button on my website. The button appears fine, but for some reason it's not working properly (it doesn't get unchecked when clicked). Can anyone help me fix this issue? I'm still learning HTML an ...

<v-time-picker> - issue with time selection

<v-time-picker> - Are you certain that the component was properly registered? If dealing with recursive components, remember to include the "name" option <div class="form-inline"> <label for="">Time</label> <v-time-pick ...

Dealing with undefined or null values when using ReactJS with Formik

Issue Resolved: It seems that Formik requires InitialValues to be passed even if they are not necessary. I'm currently working on a formik form in React, but every time I click the submit button, I encounter an error message stating "TypeError: Canno ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

Issues with uploading files in NodeJs using express-fileupload are causing errors

I created a REST API in NodeJs for File Upload which is functioning correctly, however I am facing an issue. When I upload more than 2 images, only 2 or 3 get uploaded and sometimes one gets corrupted. I suspect that the loop is running too fast causing th ...