I’m parsing XML and putting it in a simple table like this:
function showData(message) {
var str = "<table border=1 class='editable'>";
for (var i = 0; i < message.length; i++) {
str += "<tr>" + "<td>" + message[i].id + "</td>" +
"<td>" + message[i].name + "</td>" +
"<td>" + message[i].url + "</td>" +
"<td>" + message[i].desc + "</td>" +
"<td>" + "<a href='javascript:deleteRequest();' id=message[i].id>delete</a>" + "</td>" + "</tr>";
}
str += "</table>";
return str;
}
I have an tag in the last column of my table and I’m trying to set the id of the tag, or be able to get it from my deleteRequest method so I can delete that entry in the table.
1) I’m not sure if I’m setting the id correctly for the tag.
2) I’m not sure how to get the id in my deleteRequest method for the selected tag, like a sender in iOS, or maybe to pass the id in as an argument to deleteRequest(). I’m not sure which method is better. I tried to do a simple alert(arguments[0]) to see what gets passed in this case, and I get undefined. So I’m kind of lost what to do as I’m just learning Javascript. Thanks.
Try something like this for the line with the link in it:
You weren’t concatenating the value from
message[i].idinto the string you are producing, you were including the string “message[i].id”. (Note that that line ends up looking similar to the four lines of code before it.)If you pass
thisas a parameter to your function, likedeleteRequest(this)as shown above you can do this:(Obviously the
alert(el.id)is just an example of how to access theidproperty, you’ll do whatever you want with it at that point.)Note about terminology: Your question title was “Get id element of an tag” –
idis an attribute, the link is an anchor element (or “a” element), and in your html markup the anchor element is defined with an<a>tag. (Similarly, “href” is an attribute.)EDIT: I just noticed you have your JS embedded within the
hrefattribute. I’m not sure if that will work properly with thethiskeyword, but in any case a better way to do it is:Or, within your code: