Scooter Daraf Scooter Daraf - 7 months ago 35
Javascript Question

Cannot read property 'split' of undefined

Im facing a problem here when im trying to split class attribute like that

<div class='message_holder user1212 chatid142'></div>


so from my function i want to get user id (1212) and chatid ( 142)

But im getting the error in my tittle
how can i fix that pls.

function user_chat_id(){
classList = $(this).attr("class").split(/\s+/); //----here im getting the error
$.each(classList, function(index, item) {
if (item.indexOf("user") > -1) {this_id = item;}
if (item.indexOf("chatid") > -1) {this_chat_id = item;}
});
this_id = this_id.replace('user', '');
this_chat_id = this_chat_id.replace('chatid', '');
return [this_id,this_chat_id];
}


Edit :

and when i call it

$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id();
alert(this_id);
})

Answer

The problem with your current code is that the value of this in your function is undefined (if in strict mode) or set to the global context (if not in strict mode) because it's just a regular function call. So, $(this).attr("class") will just return undefined and then when you try to do .split() on it, you get the error you see.

I'd suggest a much cleaner implementation that uses a regex to get the numbers for you:

function getId(str, key) {
    var regex = new RegExp("\\b" + key + "(\\d+)\\b");
    var match = str.match(regex);
    return match ? match[1] : null;
}

function user_chat_id(obj){
    var classList = obj.className;
    var userId = getId(classList, "user");
    var chatId = getId(classList, "chatid");
    return [userId, chatId];
}

$(document).on ("mouseenter", ".message_holder", function () {
    var this_id = user_chat_id(this);
    alert(this_id);
});

In addition, the HTML you show:

<div  class='message_holder  user1212 chatid142></div>

is missing a closing quote on the class attribute. It should be:

<div class='message_holder user1212 chatid142'></div>

Working demo:

function getId(str, key) {
    var regex = new RegExp("\\b" + key + "(\\d+)\\b");
    var match = str.match(regex);
    return match ? match[1] : null;
}

function user_chat_id(obj){
    var classList = obj.className;
    var userId = getId(classList, "user");
    var chatId = getId(classList, "chatid");
    return [userId, chatId];
}

$(document).on ("mouseenter", ".message_holder", function () {
    var this_id = user_chat_id(this);
    alert(this_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div  class='message_holder  user1212 chatid142'>Put the mouse over this text</div>