$(this).attr("id").slice(-1) is working but $(this).id.slice(-1) not working


I have appended a button to the blade as a variable and the properties of that button are as follows

 var $btnDelete = $('<input />',{

                'id': 'btn_delete'+ x,
                'name':'btn_delete'+ x,
                'class':'btn btn-danger editor_remove  editor_remove_leave_types ',          
                'data-id':x  });

Note: x is just a variable(0,1,2 etc.)

This is how the button is append to a div of id="xx2" :-


Here, is the above mentioned JavaScript function of that button:

function RemoveUpdateLeaveTypes(el)


    var currentId=$(el).id.slice(-1);
    console.log('currentId '+currentId); 


After clicking on this button this error message will appear on the console

Uncaught TypeError: Cannot read property 'slice' of undefined
at RemoveUpdateLeaveTypes (leavePolicyDetails.js:944)
at HTMLInputElement.onclick (leave-policies:1)

but ,if I use this command i will have no errors

var currentId=$(el).attr("id").slice(-1);

Please explain me the conflict in here ,thanks in advance..

Show source
| javascript   | jquery   | laravel-5.3   2017-01-02 18:01 2 Answers

Answers to $(this).attr(&quot;id&quot;).slice(-1) is working but $(this).id.slice(-1) not working ( 2 )

  1. 2017-01-02 18:01

    There is no id property for the jQuery object ($(el) is a jQuery object). To get DOM element property either use jQuery prop()(or attr()) method or get DOM object by index and get the property.

    var currentId = $(el).prop('id').slice(-1);
    // or
    var currentId = $(el)[0].id.slice(-1);
    // or you can get DOM object using get() method
    var currentId = $(el).get(0).id.slice(-1);

    UPDATE : Since you are passing the DOM object as an argument and you can get id property directly from it so there is no need to wrap it using jQuery.

    // el === $(el)[0]
    var currentId = el.id.slice(-1); 
  2. 2017-01-02 19:01

    You are passing in the dom element itself as this in the html so just get the id property of that element without jQuery which does nothing to help for this situation

    var currentId= el.id.slice(-1);
    console.log('currentId '+currentId);

Leave a reply to - $(this).attr("id").slice(-1) is working but $(this).id.slice(-1) not working

◀ Go back