$ (this) .attr ("id"). slice (-1) works, but $ (this) .id.slice (-1) does not work

I added a button to the blade as a variable, and the properties of this button are as follows

var $btnDelete = $('<input />',{ 'id': 'btn_delete'+ x, 'type':'button', 'name':'btn_delete'+ x, 'class':'btn btn-danger editor_remove editor_remove_leave_types ', 'onclick':'RemoveUpdateLeaveTypes(this)', 'data-id':x }); 

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

This is how the button is added to the div id = "xx2": -

  $('#xx2').append($btnDelete); 

Here is the above JavaScript function of this button:

 function RemoveUpdateLeaveTypes(el) 

{

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

}

After clicking 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 not have errors

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

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

+5
source share
2 answers

There is no id property for jQuery object ( $(el) - jQuery object). To get the property of a DOM element, use jQuery prop() (or attr() ) or get the 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 the id property directly from it, so there is no need to wrap it with jQuery.

 // el === $(el)[0] var currentId = el.id.slice(-1); 
+5
source

You yourself pass the dom element like this in html, so just get the id property of that element without jQuery, which helps nothing in this situation.

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

Source: https://habr.com/ru/post/1262187/


All Articles