2011-11-14 97 views
4

是否可以找到並取消在字符串中沒有id的跨度?我有一個文本,其中有一些跨度其中一些有ID和其他人沒有。Javascript to untag spans without id

輸入:

<span>Hi there!</span><span id="blabla">This is a test</span> 

輸出:

Hi there!<span id="blabla">This is a test</span> 

我喜歡的JavaScript功能,但我不介意使用jQuery,如果它使事情變得更容易!

+0

你怎麼只使用拉丁字符來發音你的'名字'? – mkoryak

回答

5

您應該能夠使用:not僞選擇的組合,以及「has-attribute」選擇:

$("span:not([id])").contents().unwrap(); 

這裏有一個working example。注意HTML代碼是如何由4個span元素組成的,CSS規則適用於所有span元素,但不適用於沒有id的2 span元素,因爲它們已被上面的jQuery解包。

contents方法返回所選元素的所有子項,並且unwrap刪除父項,在這種情況下,這將是不需要的span

+0

如何在普通的JavaScript函數中使用它? –

+0

就像沒有jQuery一樣? –

+0

是的。我希望能夠在JS函數中使用它。 –

1
$("span").each(function (i) { 

if (this.id == '') { 

    alert('no have id'); 

} else { 

    alert('have id'); 
} 

}); 
1

使用jQuery,這將是非常簡單的。

$(function(){ 
    $('span').each(function(){ 
     if(typeof $(this).attr('id') == "undefined"){ 
      $(this)[0].outerHTML = $(this).html(); 
     } 
    }); 
}); 

見工作示例here ..

1

在這裏你去:

input = '<span>Hi there!</span><span id="blabla">This is a test</span>'; 

output = $('<div>').html(input).children().each(function() { 
    !this.id && $(this).replaceWith($(this).text()); 
}).end().html(); 

現場演示:http://jsfiddle.net/3EXkh/3/


更新:的AB以函數形式奧雅納代碼:

function untag(input) { 
    return $('<div>').html(input).children().each(function() { 
     !this.id && $(this).replaceWith($(this).text()); 
    }).end().html(); 
} 

現場演示:http://jsfiddle.net/3EXkh/4/

1

這裏有一個純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留給讀者練習。