How can we remove html tag by using Jquery e.g we have this html
<div><dd>hello world</dd></div>
i want to remove <dd>
tag and produce this output
<div>hello world</div>
,
You can use .replaceWith()
, for example:
$("dd").replaceWith(function() { return $(this).contents(); });
,
To remove all child nodes, retaining only the text, could also try:
$("div").html(function(i, h){ return $(h).text(); });
I forked @Nick Craver’s jsFiddle here.
,
here’s what I use. though mind you this works only if you give the div a class (or id).
var string = $('div.test').html().replace('<dd>', '').replace('</dd>', '')
$('div.test').html(string);
What this will do is simply put the contents of the div into a variable (with .html() you grab not just the text but all the html) and then strip out the dd tags, then repopulate the
edit:
here’s a better way to do it actually. using this code you don’t have to rely on a class or id being present for the div.
container = $('div').find('dd').parent();
var test = container.html().replace('<dd>', '').replace('</dd>', '')
container.html(test);
,
You could always make an if statement that checks to see if a div contains one dd element inside of it, then if that’s the case, copy the contents from the dd, remove the dd element, then inject the contents into the div.
I don’t know javascript that much, but assuming you use the right object and some simple algorithm, anything can be done!