简体   繁体   中英

How to remove specific tag in jquery?

Example:

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

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

Expecting Output:

<a>Test Message</a>

Actually this code is not working. Please help me to solve my problem.

As you've a string that contains HTML markup, you can use string replace functions to remove unwanted elements.

To remove only <font> and </font> you can use regex here.

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

Regex Explanation:

/<\\/?font>/g matches <font> and </font> strings. \\/? will match zero or one / .

Warning: The g flag in the regex will replace all the matches in the string. So, if the string contains more than one font elements, all will be removed.

Note: Using jQuery's remove() will also remove the descendants of the <font> .


You can also use jQuery's html() methods as follow:

 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> 

Use jquery unwrap to remove the parent of the a tag font Then append it to a dynamicaly created div and call the html method to get the result try:

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

https://jsfiddle.net/p0acop2k/

To remove elements and content, there are mainly two jQuery methods you should use:

  • $(html).find(selector).remove() - Removes the selected element (and its child elements)

  • $(html).find(selector).empty() - Removes the child elements from the selected element

Give more detailed code if you need more detailed answer with right selector.

Links to jQuery for remove and empty methods.

You can use it like this

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

as @Tushar commented Note: This'll also remove the anchor element inside <font> , resulting in giving empty string,

so you can use

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM