Hildy Maass
Hildy Maass

Reputation: 97

grab value of custom attribute

Is it possible to grab custom attribute like this 'something-20'

say for example it is in <div class="somecustomClass something-20"></div>

I want to grad the 19 so that I can manipulate it, because the css has block from something-1 to something-100

I used below code to retrieve tab id :

tabId = $('li').find('a').attr('href').replace('#tab', '');

is it the same approach?

Upvotes: 0

Views: 170

Answers (3)

Dawn
Dawn

Reputation: 941

Similar. What the tab id thing does is 3 things

Part 1 is selecting the right element.

Part 2 is getting the value of the attribute that contains the data we want

Part 3 is getting the specific bit of the data that we want with a regular expression

For part 1, I'm not sure what you're using to identify these blocks in order to select them.

You could have $('[class^="something"]') to get all the elements that have a class that starts with the text 'something', but that will be quite slow. If you can use something like $('.somecustomClass') it will perform better.

If you just wanted to adapt the first matching element you came across, you could do this:

var myNumber = $('.somecustomClass')[0].className.replace(/.*?\bsomething\-(\d+).*/gi, "$1");

Apologies if you are already familiar with regular expressions, but for other readers this is a breakdown of what it does:

.*? means non-greedily select zero or more characters, \b means word boundary, then it finds the text 'something-' followed by one or more digits. Putting brackets around it captures what it finds there. Just in case you have classes after than, it has .* to get zero or more characters to find them too. /gi on the end of that means look globally through the class and i means be case-insensitive. $1 as the second argument of the replace function is the captured digits.

Upvotes: 0

Danny
Danny

Reputation: 7518

If you want it to be a custom attribute I suggest you do what Jason said in his answer. But if you want to grab the something-# elements and do something with them you can do the following.

for(var i=1;i<=100;i++) {
    var el = $('.something-'+i);
    //do something with the element to manipulate it
}

Upvotes: 0

Jason P
Jason P

Reputation: 27012

That's not a custom attribute, it's a class. You'd have to get the entire class string, then probably use a regular expression to find the value you want.

It would be easier to use data- attributes:

<div class="somecustomClass" data-something="20"></div>

JS:

var value = $('.somecustomClass').data('something'); // 20

Upvotes: 4

Related Questions