0

I have a div which contains an anchor tag as below.

<div id="sideTabs">
        <a href="#" type="click" >
            Click Here
        </a>
</div>

For some reasons I cannot set id or class on anchor tag and there is a attribute type in the anchor tag.

I have a CSS class

.selected {
            background: rgb(41, 41, 59);
            color: #fff;
}

I want to add this class dynamically when I click on anchor tag.
I know how to add a CSS class with reference to id and class.

$(#"id of anchortag").attr("class", selected); 

As I do not have id attribute can some one explain me how to add a CSS class with some other attribute, in my case type.

CrazyCoder
  • 2,194
  • 10
  • 44
  • 91

4 Answers4

4

Use this selector a[type="click"] to get that/those element(s) and use the function addClass to add a new class to that/those element(s).

$('a[type="click"]').addClass('selected')
Ele
  • 33,468
  • 7
  • 37
  • 75
3

You can use $("a[type='click']") to set click listener on...

$("a[type='click']").on("click", function() {
  $(this).addClass("selected");
})
.selected {
  background: rgb(41, 41, 59);
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sideTabs">
  <a href="#" type="click">
            Click Here
        </a>
</div>
void
  • 36,090
  • 8
  • 62
  • 107
1

You need to wrap the selector and the arguments to attr in quotes because they're strings

$("#id of anchortag").attr("class", "selected"); 
vityavv
  • 1,482
  • 12
  • 23
1

You add class by using .addClass('selected');

so $('#id-you-have').addClass('selected');

But keep in mind that your a tag doesn't have an ID

zmuci
  • 518
  • 1
  • 5
  • 21