Scooter Daraf Scooter Daraf - 7 months ago 15
Javascript Question

Using this with class that contains some special string

I have checked this question

But it didnt work if i want to look if that class start by special string.

im trying to achieve something like this

<div class = "message_holder user12121 chatid47">


and when clicking

$(document).on ("mouseenter", ".message_holder", function () {
this_id = $(this).find("div[class*='user']");
alert(this_id.replace('user', '')); // i want to alert 12121
alert(this_id); // tried this also
})


but didnt work . im getting [object OBJECT] error.

if it was a fixed class this could work

$(this).find(".subclass");

Answer

you need to add .attr("class")

$(document).on ("mouseenter", ".message_holder", function () {
   var this_id;
  
  var classList = $(this).attr("class").split(/\s+/);
  $.each(classList, function(index, item) {
    if (item.indexOf("user") > -1) {this_id = item;}
  });
   alert(this_id.replace('user', ''));
 })
.message_holder{
  height:200px;
  width:200px;
  background:silver;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message_holder user1235 chat77"></div>

EDIT Code has been updated to take into consideration html.

EDIT 2 Used an idea from here to create an array of classes. Get class list for element with jQuery

Comments