如何判断一个元素是否为“br”?

4

如何判断一个元素是否为“br”? 我尝试使用 .attr("type") 和 .type() 获取它,但始终返回 undefined! 对于 input 或 button 元素有效,但对于 br 元素无效。


如果 (elem.localName == 'br') {...} - Ram
.attr("type") 在处理输入框或按钮时并不是以同样的方式工作:它并不能告诉你元素是 <input> 还是 <button>,而是告诉你这个 <input><button> 的类型。 - nnnnnn
4个回答

9
使用.tagName.nodeName属性,然后将其值与"BR"进行比较。

这确实是最有效的方法。仅为了执行与其进行比较而将对象转换为jQuery比使用本机JS要慢得多。 - Ohgodwhy
但是OP可能已经在这里使用$(element)了,所以不需要进行转换(再次强调,可能不需要)。 - raina77ow
3
请确认将其大写为“BR”。 - cake

6

你可以尝试使用$(element).is('br'),例如:

<div class='tested' id='first'>
  <br class='tested' id='second' />
</div>

...
$('.tested').each(function() {
  var id = this.id;   
  if ($(this).is('br')) {
    console.log(id + ' is <br>');
  }
  else {
    console.log(id + ' is not <br>');
  }
});
// first is not <br>
// second is <br>​

我已经尝试过这个,但它总是返回false console.log($(this).parent().children().is('br')); - mrmoor
@mrmoor 因为children方法返回给你一个元素集合,因此你应该使用类似于这样的方式来对其进行筛选。 - raina77ow

4

通过 element.tagName 可以获取标签的名称。

if (element.tagName=="br")

0
<div id="test">
    <br>
</div>

--

var tag = $("#test").children().first().prop('tagName'); //returns BR

代码片段

var isTag = $("#test").children().first().is('br');  //returns true/false

小提琴


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接