[英]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();
你可以這樣使用
$(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.