簡體   English   中英

如何刪除jQuery中的特定標簽?

[英]How to remove specific tag in jquery?

例:

html = '<font><a>Test Message</a></font>';

html = html.find('font').remove();

預期輸出:

<a>Test Message</a>

實際上,此代碼無法正常工作。 請幫助我解決我的問題。

當您擁有包含HTML標記的字符串時 ,可以使用字符串替換功能刪除不需要的元素。

要僅刪除<font></font> ,可以在此處使用正則表達式。

 html = '<font><a>Test Message</a></font>'; html = html.replace(/<\\/?font>/g, ''); document.getElementById('result').innerText = html; console.log(html); 
 <pre id="result"></pre> 

正則表達式說明:

/<\\/?font>/g匹配<font></font>字符串。 \\/? 將匹配零或一/

警告: regex中的g標志將替換字符串中的所有匹配項。 因此,如果字符串包含多個font元素,則所有font元素都將被刪除。

注意:使用jQuery的remove()還將刪除<font>的后代。


您還可以如下使用jQuery的html()方法:

 html = '<font><a>Test Message</a> </font>'; html = $(html).html(); // To show result on page $(document.body).text(html); console.log(html); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

使用jquery unwrap刪除a標記font的父代,然后將其附加到動態創建的div並調用html方法以獲取結果try:

  html =  $('<div>').append($(html).find('a').unwrap()).html();

https://jsfiddle.net/p0acop2k/

要刪除元素和內容,主要應使用兩種jQuery方法:

  • $(html).find(selector).remove() -刪除選定的元素(及其子元素)

  • $(html).find(selector).empty() -從選定元素中刪除子元素

如果您需要使用正確選擇器的更詳細答案,請提供更詳細的代碼。

鏈接到jQuery的removeempty方法。

你可以這樣使用

$(html).find('font').remove();

如@Tushar注釋:注意:這還將刪除<font>內的anchor元素,從而產生空字符串,

所以你可以使用

html = '<font><a>Test Message</a></font>';
new_html = $(html).find('a').clone(); // this is just an anchor
// now your new html is <a>Test Message</a>
html = $('<font><a>Test Message</a></font>');
html.find('font').contents().unwrap();
console.log(html.html());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM