Right, idiot moment coming up. I've done a search, but can't find the right solution.
I've got a jQuery selector selecting a class, maybe an ID, in fact it could be anything, this selector is fed into a function I'm programming.
I need to be able to figure out the type of each matched element, for example:
<div class="target"></div>
Would return div, and
<input class="target" />
开发者_运维问答Would return input, simple right?
Well you'd have thought so, but I cannot seem to find the solution.
Any help would be greatly appreciated :-)
You need to get the underlying DOM element and access the tagName
property. For example,
alert($("#target").get(0).tagName);
// -> DIV
Be aware that browsers will return the tag name in uppercase, so something like this would cause you a bit of grief:
if ($("#target").get(0).tagName == "div") { alert("DIV!"); }
$.fn.tagName = function() {
return this.get(0).tagName;
}
alert($('#testElement').tagName());
To explain a little bit more of why your original example didn't work, the each() method will always return the original jQuery object (unless the jQuery object itself was modified). To see what is happening in each with your code, here is some pseudocode that shows how the each() method works:
function each(action) {
for(var e in jQueryElements) {
action();
}
return jQueryObject;
}
This is not how each() really gets implemented (by a long shot probably), but it is to show that the return value of your action() function is ignored.
try:
$("yourelement").is("input")
or:
if ($(this).is('input:checkbox'))
etc.... where appropriate
精彩评论