0

Before I get to my question, consider the following code, which seems to work with jQuery:

var $element = $('.input-fieldset');

$element.each(function(){
  $(this)[0].classList.add("input-fieldset-awesome");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="pay" class="input-fieldset"></fieldset>
<fieldset id="address" class="input-fieldset"></fieldset>

I discovered that the above seemed to work after first running into problems with this:

var $element = $('.input-fieldset');
$element.classList.add("input-fieldset-awesome");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="pay" class="input-fieldset"></fieldset>
<fieldset id="address" class="input-fieldset"></fieldset>

Which throws an error:

Cannot read property 'add' of undefined

In my struggle to find a solution, I found that someone else had a similar problem here, but in that example, they weren't using jQuery. Also, it was found to be a duplicate question of this, which the top answer suggested that $('.myElement').css('size', '100px'); was possible. But if that should work, then why doesn't this:

$('.input-fieldset').classList.add("input-fieldset-awesome");

That was the first question; my other question is this: in my working solution above, I used "[0]" to de-reference the first element in the $(this) object which I know should have only one element in it, but is that really the best solution? (It seems strange to me that I should need the "[0]" at all...)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Damian Green
  • 633
  • 2
  • 8
  • 13

2 Answers2

1

.classList is a property on native HTMLElements. $('<selector>') returns a jQuery collection, which is quite different. jQuery collection methods do not have the same names as element methods.

jQuery does have a function that lets you add classes, though, via addClass, which will add the selected class to every element in the collection:

var $elements = $('.input-fieldset');
$elements.addClass("input-fieldset-awesome");
.input-fieldset-awesome {
  border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="pay" class="input-fieldset"></fieldset>
<fieldset id="address" class="input-fieldset"></fieldset>

Note that since jQuery collections are collections and not single elements (generally), it would be good to name the variables appropriately - that is, for example, var $elements rather than var $element.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

jQuery has it's own class changing methods like addClass(), removeClass() and toggleClass()

Mixing native dom methods and jQuery ones can make your code base hard to read through and confusing.

For example it makes no sense to do $(this)[0] which just returns this

Use one or the other and stick to the same approach throughout.

charlietfl
  • 170,828
  • 13
  • 121
  • 150