What is the best way to access elements of a certain class that begin with a specific string?

Here's the scenario: I have a group of elements that each have multiple classes assigned to them. Take a look at this example:

<input class="etape btn-info others">
<input class="etape btn-inverse others">
<input class="etape btn-danger others">

I'm looking for a way to write jQuery code that will help me achieve the following task...

$(".etape").click(function(){
   $(this).get("the class that starts with btn-")
   // and then save this value in a variable for later use
});

Answer №1

You have the option to either utilize Regular Expression or split the class name using the split method.

$(".etape").click(function(){
   var classes = $.grep(this.className.split(" "), function(v, i){
       return v.indexOf('btn') === 0;
   }).join();
});

Visit this JSFiddle link for more information

Answer №2

Another option to consider:

$(".step").click(function () {
    var selectedClass = $(this).attr("class").match(/btn[\w-]*\b/);
    console.log(selectedClass); 
});

Opting for match over grep...

Answer №3

 // Selecting only inputs with a class
 $('input[class]').click(function(){  
   var myClass;
   // Storing all applied classes in classNames
   var classNames = $(this).attr('class').split(/\s+/);  

     // Looping through each class  
     $.each(classNames, function(index, item) {
        // Checking for classes that start with btn-
        if(item.indexOf("btn-") == 0){
          // Saving the class
          myClass = item;
        }
     });

  });

Live Demo

Answer №4

Storing those values in the data attribute would be a more efficient approach:

<input class="etape others" data-btntype="info">
<input class="etape others" data-btntype="inverse">
<input class="etape others" data-btntype="danger">

Afterwards:

 $(".etape").click(function(){
     var myBtnType = $(this).data('btntype');
 });

View demo on jsFiddle

Answer №5

One option could be to create a separate class for btn. Nonetheless, the following code will also achieve the desired outcome.

$("div[class^='btn-']")

Answer №6

Check out this code snippet:

$('input[class*='btn']').attr("class");

Answer №7

I have successfully optimized @Vohuman's function to make it reusable:

// getClassStartsWith(classes, startswith);
// Example: getClassStartsWith('item w-2 h-4 hello', 'h-');
function getClassStartsWith(t, n) {
    var r = $.grep(t.split(" "), function(t, r) {
        return 0 === t.indexOf(n)
    }).join();
    return r || !1
}

For example...

HTML :

<div class="item w-2 h-4 hello"></div>

JS :

var $element = $('.item');
var classes = $element[0].className;
var getHeight = getClassStartsWith(classes, 'h-');

This will output h-4. If no class starts with h-, it will return false

Demo : http://jsbin.com/mijujunaca/edit?js,console

Answer №8

This handy function utilizes regular expressions to retrieve Class, ID, Data, and various other attributes.

$.fn.Get_Attr_Regex = function(Pattern,Type) 
{
    Type = Type || 'class';
    var List_Str = this.attr(Type);

    if(typeof List_Str !== typeof undefined && List_Str !== false) 
    {
        var regex = new RegExp(Pattern, "g");
        var List_Array = List_Str.split(" ");
        for(var i = 0; i < List_Array.length; i++)
        {
            if(regex.test(List_Array[i]))
            {
                return List_Array[i];
            }
        }
    }
    return false;
};

To use it

$('.T_Header').Get_Attr_Regex('btn.*','class'); // => returns the class value starting with btnxxx

or

$('.T_Header').Get_Attr_Regex('btn.*','id');  // => returns the id value starting with btnxxx

or

$('.T_Header').Get_Attr_Regex('btn.*','data-info'); // => returns the data attribute value starting with btnxxx

Answer №10

Consider a CSS class that begins with btn and is not the first specified class:

Here is a working example: http://jsfiddle.net/c9Tdx/

$("input[class^='btn'],input[class*=' btn']").each(function(){
     //do something
});

Answer №11

Give this a shot,

Check if the selector class name starts with 'classToStartFrom':

if($(selector).attr("class").lastIndexOf("classToStartFrom") == 0)
   return "this selector class name starts with 'classToStartFrom'";
else
   return "this selector class name doesn't start with 'classToStartFrom'";

Note that the code has not been tested.

Answer №12

If you prefer to achieve this on page load rather than clicking the element, you can utilize the code provided below:

var allClasses = '';
jQuery(".etape").each(function() {
      allClasses += $.grep(this.className.split(" "), function(classItem) {
           return classItem.indexOf('btn') === 0;
      }).join() + '|';
});
console.log(allClasses);

You can replace "|" with any other symbol that you would like to use for joining the class names.

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

Having trouble importing CSS in ReactJS?

While working on my project based on next.js, I encountered a situation where loading CSS in other pages was successful: import css from './cssname.css'; <div className={css.myclass}></div> However, now that I am implementing a ligh ...

How can I confirm that all elements have been properly reset to their original positions prior to making any further adjustments to them?

In need of some creative brainstorming, I'm working on a website design featuring ten overlapping cards. When the mouse hovers over a card, it expands while others move away. My goal is for each card to return to its original position once the cursor ...

No links were detected in the page source

I am attempting to locate URL links within the page source of this website. http://data2.7m.cn/database/index_en.htm However, I have been unable to find any links in the page source or even after trying Ajax calls with Firebug. There are no links for cou ...

Emphasize identical terms in AngularJS through bold formatting

I am facing a situation where I need to apply bold formatting to specific words in an HTML string (editorData) using AngularJS, based on whether they match certain keywords (data or dataArray). It is important to note that the case of the words in editorD ...

Randomly positioning an image while the page is loading

I've been developing a portfolio website to showcase my design work, but I've encountered a minor issue. My goal is to have the images load in random positions and then make them draggable using Dragabilly. However, sometimes all the images end ...

What is the best way to ensure that the child flex box matches the height of the parent flex box by 100%?

As a beginner, I'm venturing into creating an experimental site for myself. However, I am facing an issue where the .menu-container does not seem to stretch 100% the height of the .container. You can view the code on jsfiddle: https://jsfiddle.net/y1 ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Passing dynamic scope from Angular to a directive is a seamless process

I am working with a directive that retrieves an attribute value from an http call in the following manner: Controller app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); ...

Issue with AJAX call not functioning properly within PHP document

I've encountered an issue with a form that triggers an ajax call upon clicking the submit button. The ajax function is located within a PHP file as I need to populate some variables with data from the database. However, the before / success callbacks ...

Using jQuery to modify a CSS property when a specific option is chosen

I'm currently working on creating an option dropdown menu and I've hit a roadblock trying to display a textbox only when the 'other' option is selected. Here's what I have so far: <span id="con-country"><label for="count ...

Exploring the Pathways of a Website's Architecture

Recently, I stumbled upon a website that piqued my interest. I am looking to send POST requests to it and then retrieve the HTML code from subsequent GET requests. Is there a way for me to uncover the organization of these routes? My plan is to perform m ...

Using a JSONArray in an Ajax Loop

I am having trouble looping through a JSONArray in my JavaScript file. Can someone please assist me? Here is my servlet code: ArrayList<Campionato> campionati = DBManager.getInstance().getCampionatoDao().query(); JSONArray jsonArray = new JSONA ...

Enable lightbox functionality prior to all images being fully loaded

I have a large number of images (thumbnails) on my website and I am using the Featherlite lightbox plugin. However, when I click on one of the loaded images while they are still loading, the lightbox does not work as expected. Instead of opening in a modal ...

onpageshow event behaves as expected exclusively on webkit browsers (triggers function solely when visible on the screen)

I am inserting an HTML file using an object tag. The encompassing div of the object tag is hidden with a display:none property. However, I encounter an issue where the onpageshow event that I placed on the body tag of the HTML object behaves differently a ...

When using the resize property in monaco-editor, it may result in editor popups being obscured or

My current task involves utilizing the deltaDecorations method to display errors in my editor. Feel free to check out my code here: https://gist.github.com/dinager/41578bd658b60cc912a6023f80431810 Below is the output: https://i.sstatic.net/Dtj9A.png ...

Optimal Procedure for New Users Form (Jade / Angular) in HTML

I'm currently working on integrating a form into my app for users to create tasks. This form should only appear the first time a user attempts to create a task. As someone who is not very experienced with frontend development, I find myself wondering ...

Utilizing a factory as the data source in angular-datatables leads to unexpected errors

Is it possible to use a factory as a source data in angular-datatables? Basically, I want to retrieve data in a variable and use it as the data source. UPDATED (06/22/2016) This is my updated factory: statisticsModule.factory('globalFactory&apos ...

md-datepicker incorrect input- AngularJS

When selecting a non-existent date manually in the input, the calendar shows the date I expect but the input does not. Here is the code snippet: <md-datepicker name="startDate" class="custom-datepicker" ng-model="models.startDate" md-placeholder="Ente ...

The data sent to the controller through AJAX is empty

I am facing an issue while trying to return a List of objects back to my controller. The problem is that the list appears as null when it reaches the controller. Below is the structure of what I am doing: Controller Action Signature [HttpGet] public Acti ...

What could be the reason my SVG images are not displaying?

My website contains SVGs that are not loading consistently. I acquired some from freeicons/icon8 and created a couple using Inkscape. Initially, I inserted them using HTML but switched to CSS after doing research online on how to ensure they load properly ...