我希望能够识别文本字符串的第一个子元素何时是元素或文本节点,例如:
我正在考虑这样做:$('<span>'+my_html_string+'</span>').children().is('*')
但这并不总是有效。
1:第一个子元素是文本。一些例子:
<span>some text<span> //works using above code
<div>here is some <span>text</span></div> //fails using above code
<pre>check out my text</pre> //works
2:第一个子元素是任意元素,一些示例:
<div><span>I am an element</span></div> //works
<span><div>first child div</div>understand?</span> //works
如何检测元素中的第一项是文本还是元素?
最佳答案
我建议使用一些简单的 JavaScript(尽管与 jQuery 结合用于相关节点/元素的迭代)。以下内容未经测试,但我认为已经说明了要点:
function firstChildIs(el) {
if (!el) {
return false;
}
else {
switch (el.firstChild.nodeType) {
case 1:
return 'Element is an element';
break;
case 2:
return 'Element is an attribute node';
break;
case 3:
return 'Element is a textNode';
break;
case 4:
return 'Element is a CDATA section node';
break;
case 5:
return 'Entity reference node';
break;
case 6:
return 'entity node';
break;
case 7:
return 'processing instruction node';
break;
case 8:
return 'comment node';
break;
case 9:
return 'document node';
break;
case 10:
return 'document type node';
break;
case 11:
return 'document fragment node';
break;
case 12:
return 'document notation node';
break;
default:
return 'Something horrible has probably happened...';
break;
}
}
}
并调用:
$(elementSelector).each(
function(){
console.log(firstChildIs(this));
});
编辑是因为我认为使用数组可能比使用开关更容易:
function firstChildIs(el) {
if (!el) {
return false;
}
else {
var nodetypes = ['element', 'attribute', 'text',
'CDATA section', 'entity reference',
'entity', 'processing instruction',
'comment', 'document', 'document type',
'document fragment', 'document notation'];
return nodetypes[el.firstChild.nodeType - 1] || 'something really unexpected happened';
}
}
按照前面所示的相同方式进行调用,如果您想添加单词“node”,请记住将其添加到函数返回的值中。
还值得记住的是,一些(尽管我不认为全部)浏览器确实将打开标签之间的空白(换行符和制表符)报告为文本节点,所以它完全是可能您必须在评估 firstChild
的节点类型之前修剪空白。
引用文献:
关于jquery - 如何检查节点是元素还是文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14086917/