【发布时间】:2011-09-25 00:24:58
【问题描述】:
如何检查$(this) 是div、ul 还是blockquote?
例如:
if ($(this) is a div) {
alert('its a div!');
} else {
alert('its not a div! some other stuff');
}
【问题讨论】:
标签: javascript jquery html css
如何检查$(this) 是div、ul 还是blockquote?
例如:
if ($(this) is a div) {
alert('its a div!');
} else {
alert('its not a div! some other stuff');
}
【问题讨论】:
标签: javascript jquery html css
类似这样的:
if(this.tagName == 'DIV') {
alert("It's a div!");
} else {
alert("It's not a div! [some other stuff]");
}
【讨论】:
$(this).get(0) 等同于this 但没有开销吗?
this 也不是。 $(this).get(0) 接受this(一个普通的 JS DOM 节点),将其转换为 jQuery 对象,运行 .get(0),它选择 jQuery 对象中的第一个常规 DOM 节点......也就是说,带你回到你所在的位置开始了。 this.tagName = $(this)[0].tagName = $(this).get(0).tagName.
没有 jQuery 的解决方案已经发布,所以我将发布使用 jQuery 的解决方案
$(this).is("div,ul,blockquote")
【讨论】:
没有 jQuery 你可以说this.tagName === 'DIV'
请记住,tagName 中的“N”是大写的。
或者,使用更多标签:
/DIV|UL|BLOCKQUOTE/.test(this.tagName)
【讨论】:
检查该元素是否为DIV
if (this instanceof HTMLDivElement) {
alert('this is a div');
}
HTMLUListElement 与 UL 相同,HTMLQuoteElement 用于区块引用
【讨论】:
if(this.tagName.toLowerCase() == "div"){
//it's a div
} else {
//it's not a div
}
编辑:在我写的时候,给出了很多答案,对不起,双重的
【讨论】:
$(this).tagName 完全是错误的。你的意思是$(this).attr('tagName')
通过 jQuery 你可以使用$(this).is('div'):
根据选择器、元素或 jQuery 对象检查当前匹配的元素集,如果这些元素中至少有一个与给定参数匹配,则返回 true。
【讨论】:
其中一些解决方案有点过火了。您只需要来自常规旧 JavaScript 的 tagName。再次用 jQuery 重新包装整个内容并没有真正获得任何好处,尤其是在库中运行一些更强大的函数来检查标签名称。如果你想在这个页面上测试它,这里有一个例子。
$("body > *").each(function() {
if (this.tagName === "DIV") {
alert("Yeah, this is a div");
} else {
alert("Bummer, this isn't");
}
});
【讨论】:
let myElement =document.getElementById("myElementId");
if(myElement.tagName =="DIV"){
alert("is a div");
}else{
alert("is not a div");
}
/*What ever you may need to know the type write it in capitalised letters "OPTIO" ,"PARAGRAPH", "SPAN" AND whatever */
【讨论】:
我正在增强 Andreq Frenkel 的答案,只是想补充一些,但它变得太长了所以在这里消失了......
考虑 CustomElements 扩展现有元素并仍然能够检查元素是否是 input,这让我认为 instanceof 是解决此问题的最佳解决方案。
但应该注意,instanceof 使用引用相等,因此父窗口的 HTMLDivElement 将与其 iframe(或影子 DOM 等)不同。
要处理这种情况,应该使用选中元素自己的窗口类,例如:
element instanceof element.ownerDocument.defaultView.HTMLDivElement
【讨论】:
老问题,但由于没有一个答案提到这一点,没有 jquery 的现代替代方案可能只是使用 CSS 选择器和 Element.matches()
element.matches('div, ul, blockquote');
【讨论】:
尝试使用tagName
【讨论】: