Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .attr() multiple attributes

Attempted to retrieve attirbutes of an element using the .attr function. I dynamically create an input element using and assign the value to the class attribute.

$('.item-selection-amount').click(function(){
    console.log($(this).attr('class'));
});

This will return:

item-selection-amount ui-corner-all price
item-selection-amount ui-corner-all 66.00

price is always different, but is it possible to pull the third value of the class attribute such as attr('class[2]') etc?

like image 410
JS1986 Avatar asked Dec 16 '22 16:12

JS1986


2 Answers

You are using class attribute incorrectly.
It is intended to be used for visual presentation.

What you want to do is to attach data to an element.

For that purpose you can use HTML5 data- attributes:

$('.item-selection-amount').data('price', 66.00);
// ... later
$('.item-selection-amount').click(function(){
  console.log( $(this).data('price') );
});

If you want to add price to the element just render the HTML similar to one below on the server:

<li class='item-selection-item' data-price='66.00'>Something</li>
like image 163
Dmytrii Nagirniak Avatar answered Jan 06 '23 12:01

Dmytrii Nagirniak


Do you have prices included in HTML as CSS classes? You can't really rely on the order of CSS class names, unless you set them up in HTML and never change in JavaScript. You should generally manipulate and test CSS classes in jQuery using .addClass(), .removeClass(), .toggleClass() and .hasClass().

For storing data consider using data- attributes:

<span class="item-selection-amount" data-price="66.00">...</span>

and it would be easy to use with jQuery:

$('.item-selection-amount').click(function(){
    console.log($(this).data('price'));
});

See DEMO. Instead of span you can use whatever tag you are using right now.

like image 26
rsp Avatar answered Jan 06 '23 12:01

rsp