Scooter Daraf Scooter Daraf - 2 years ago 66
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


Answer Source

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', ''));
<script src=""></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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download