0

Hi what i'm trying to do is add a class to a div with specific name attribute, for example i have a div like this.

<div class="box" name="box-1"></div>

<div class="box" name="box-2"></div>

now how to add a class to that div with that attribute, i mean add class to a div with name attribute of box-1, how can i do that?

the preacher
  • 285
  • 3
  • 7
  • 23
  • Uae the [attribute selector](https://api.jquery.com/attribute-equals-selector/). However `div` elements do not have a `name` attribute, so the bigger problem is that your HTML is invalid. Use a data attribute instead, ie. `data-name="box-1"`, or better still, an `id` – Rory McCrossan Jan 21 '20 at 09:23

1 Answers1

2

You can use div[name ="box-2"]

$('div[name ="box-2"]').addClass('myclass');
.box{width:50px; height:50px;}
.myclass{background:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" name="box-1">Box 1</div>

<div class="box" name="box-2">Box 2</div>
Lalji Tadhani
  • 14,041
  • 3
  • 23
  • 40
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37