Alexander Prisazhny
Alexander Prisazhny

Reputation: 154

Check, whether an object has class with a certain number in its name

My situation is the following: I have several classes with names obj1, obj2, ob3 and an output object. When one of obj# is clicked, i want a corresponding text to be added in output object. Here is my code:

<div class="obj obj1">Object 1</div>
<div class="obj obj2">Object 2</div>
<div class="obj obj3">Object 3</div>
<div class="output"></div>

And JavaScript:

function whichObject($obj) {
for (i = 0; i < 3; i++) {
  switch($obj.hasClass("obj" + (i+1).toString())) {
    case "obj1":
      $(".output").text("Object 1");
      break;
   case "obj2":
      $(".output").text("Object 2");
      break;
   case "obj3":
      $(".output").text("Object 3");
      break;
   }
}

$(".obj").on("click", function () {
   whichObject($(this));
});

I need the loop because the number of obj# objects may increase over time and I cannot predict a certain amount of obj# objects.

I'm surely missing something or the whole approach is wrong.

Upvotes: 1

Views: 60

Answers (2)

Alexander Prisazhny
Alexander Prisazhny

Reputation: 154

So, if somebody is interested I solved it this way:

function whichObject(obj) {
  var $obj = $(obj);
  if ($obj.attr("id") === "obj1") {
    $(".output").text("Object 1");
  } else if ($obj.attr("id") === "obj2") {
    $(".output").text("Object 2");
  } else if ($obj.attr("id") === "obj3") {
    $(".output").text("Object 3");
  } 
}

$(".obj").on("click", function () {
whichObject(this);
});

while adding the following IDs to my HTML:

<div class="obj" id="obj1">Object 1</div>
<div class="obj" id="obj2">Object 2</div>
<div class="obj" id="obj3">Object 3</div>
<div class="output"></div>

Upvotes: -1

Taplar
Taplar

Reputation: 24965

$('.obj').on('click', function(e){
  $('.output').text(e.target.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="obj obj1">Object 1</div>
<div class="obj obj2">Object 2</div>
<div class="obj obj3">Object 3</div>
<div class="output"></div>

Upvotes: 2

Related Questions