0

i wanted to remove meta tag with parent paragraph tag in below code.

<p>
    <meta content="text/html; charset=unicode" http-equiv="Content-Type" />
</p>
<p>
    <meta content="MSHTML 8.00.6001.18702" name="GENERATOR" />
</p>
<div>
    <img border="0" src="http://localhost:15978/TestImages/Que_152_0/51099.jpg" /></div>
<br />
<br />
<div>
    write something on the pic shown.</div>

I can remove meta tag using

.replace(/<meta([^>]+)>/g, '');

regular expression, wanted regular expression to replace meta with parent paragrapy tag

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
Haneep CR
  • 141
  • 5
  • 12

2 Answers2

1

This can be easily accomplished with this short jQuery command:

$('p meta').remove();

Finding <meta> tags that are children of <p> is easily described in a selector, and remove() will remove all matching elements at once.

It becomes a bit more complicated when your HTML is in a string, but it's still not too bad:

var content = '...insert above html here...';

// insert into a div to parse as HTML
var $content = $('<div />').html(content);

// find all <meta> tags inside <p> and remove them
$content.find('p meta').remove();

// convert contents back to a string
content = $content.html();

Working fiddle: http://jsfiddle.net/WVWPS/

Although the above code works for me, there may be problems in some browsers caused by the fact that <meta> is not a valid HTML element in the body of a document. This question suggests that jQuery may not be able properly create elements like <meta> in some cases.

If you run into browser-specific problems, you can try something like this:

var content = '...insert above html here...';

// convert <meta> tags to <span> tags with a "meta" class
content = content.replace(/<meta /g, '<span class="meta" ');

// insert into a div to parse as HTML
var $content = $('<div />').html(content);

// find all .meta elements inside <p> and remove them
$content.find('p .meta').remove();

// convert contents back to a string
content = $content.html();

Working fiddle: http://jsfiddle.net/a4Wa3/

Before we parse the HTML, we're doing a string-replace to convert the <meta> tags into <span class="meta"> tags instead.

Note that this last option is a very fragile solution, and could break if you change how the meta tags are generated. As a general rule, manipulating HTML with regular expressions or other string functions should be avoided, as it can have serious side effects.

Community
  • 1
  • 1
jcsanyi
  • 8,133
  • 2
  • 29
  • 52
0

You could do the following in jQuery,

$("meta").each(function () {
    var $this = $(this);
    if ($this.parents("p").length > 0) {
        $this.remove();
    }
});

Test Link

painotpi
  • 6,894
  • 1
  • 37
  • 70