Javascript to untag spans without id
是否有可能找到并取消字符串中没有id的跨度? 我有一个包含大量跨度的文本,其中一些有ID,而另一些则没有。
输入:
Hi there!This is a test
输出:
Hi there!This is a test
我更喜欢JavaScript函数,但我不介意使用jQuery,如果它让事情变得更容易!
您应该能够使用:not
pseudo-selector和“ has-attribute ”选择器的组合:
$("span:not([id])").contents().unwrap();
这是一个有效的例子 。 请注意HTML代码是如何由4个span
元素组成的,CSS规则适用于所有span
元素,但不适用于没有id
的2 span
元素,因为它们已被上面的jQuery解包。
contents
方法返回所选元素的所有子元素,并且unwrap
将删除父元素,在这种情况下,父元素将是不需要的span
。
$("span").each(function(){ if (this.id == "") $(this).replaceWith(this.innerHTML); })
使用jQuery这将非常简单。
$(function(){ $('span').each(function(){ if(typeof $(this).attr('id') == "undefined"){ $(this)[0].outerHTML = $(this).html(); } }); });
看这里的工作示例..
$("span").each(function (i) { if (this.id == '') { alert('no have id'); } else { alert('have id'); } });
这是一个纯JavaScript解决方案,FWIW:
Array.prototype.forEach.call(el.getElementsByTagName('span'), function(element){ var children; if( ! element.id){ children = document.createDocumentFragment(); while(element.firstChild){ children.appendChild(element.firstChild); } element.parentElement.replaceChild(children, element); } });
在没有Array.prototype.forEach
浏览器Array.prototype.forEach
这项工作留给读者阅读。
干得好:
input = 'Hi there!This is a test'; output = $( '' ).html( input ).children().each( function () { !this.id && $( this ).replaceWith( $( this ).text() ); }).end().html();
现场演示: http : //jsfiddle.net/3EXkh/3/
更新:以上函数forms的代码:
function untag( input ) { return $( '' ).html( input ).children().each( function () { !this.id && $( this ).replaceWith( $( this ).text() ); }).end().html(); }
现场演示: http : //jsfiddle.net/3EXkh/4/