如果HTML元素可以包含一些文本,那么我可以使用纯粹的JavaScript或者jQuery来测试一个干净和健壮的方法吗? < br> ,< hr> 或< tr> 不能包含文本节点,而< div> ,< td> 或< span> 可以。
测试此属性的最简单的方法是控制标签名称。但这是最好的解决方案吗?我认为这是最差的一个...
编辑:为了澄清问题的意义,需要指出的是,完美的答案应该考虑两个问题:
显然,前面列表中每个点都有一个子答案。 >
解决方案void elements的W3标准指定:
空虚元素 area,base,br,col,embed,hr,img,input,keygen,link,menuitem,meta,param,source,track,wbr
显然,还有一些非官方的标签。
您可以使用黑名单并使用 .prop('tagName')获取标签名称:
(function($){ var cannotContainText = ['AREA','BASE','BR','COL','EMBED','HR','IMG' 'INPUT','KEYGEN','LINK','MENUITEM','META','PARAM','SOURCE','TRACK','WBR','BASEFONT','BGSOUND','FRAME','ISINDEX ]; $ .fn.canContainText = function(){ var tagName = $(this).prop('tagName')。toUpperCase(); return($ .inArray(tagName,cannotContainText)== -1); }; }(jQuery)); $('< br>')。canContainText(); // false $('< div>')。canContainText(); // true这里您还可以添加自己的标签到 cannotContainText (例如添加< tr> 这不是正式的一个void元素,因为它不匹配规范一个void元素是一个元素,其内容模型永远不允许它具有内容任何情况下,虚空元素都可以有属性。)
Is there a clean and robust way in which I can test (using pure javascript or also jQuery) if an HTML element can contain some text?
For instance, <br>, <hr> or <tr> cannot contain text nodes, while <div>, <td> or <span> can.
The simplest way to test this property is to control the tag names. But is this the best solution? I think it is one of the worst...
EDIT: In order to clarify the sense of the question, need to point out that the perfect answer should consider two problems:
Obviously, there is a sub-answer for each point of the previous list.
解决方案The W3 standard for "void elements" specifies:
Void elements area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr
And apparently there's some unofficial tags as well.
You can make a black list and use .prop('tagName') to get the tag name:
(function ($) { var cannotContainText = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX']; $.fn.canContainText = function() { var tagName = $(this).prop('tagName').toUpperCase(); return ($.inArray(tagName, cannotContainText) == -1); }; }(jQuery)); $('<br>').canContainText(); //false $('<div>').canContainText(); //trueHere you can also add your own tags to cannotContainText (eg. to add <tr> which is not officially a void element as it doesn't match the specification "A void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes.").
更多推荐
测试元素是否可以包含文本
发布评论