Reputation: 1978
I've been trying to use jquery to apply a function to each html tag with some class inside a html object (imported from a file), but I can't get it to work. I've looked through several other questions on SE but couldn't find a solution to my problem.
The html variable contains much more code in my actual use case, but this
html = '<pre class = "classy"> text </pre>'
$(html).find('.classy').each( function (x) {
$('<pre class = "classy">' + '<h1>' + x + '<h1>' + '</pre>')
})
'<pre class = "classy"> text </pre>'
where the intended output was more like
'<pre class = "classy"> <h1> text </h1> </pre>'
.replaceWith didn't work either, so I presume I'm doing something conceptually wrong. Any solutions/tips?
Upvotes: 0
Views: 87
Reputation: 388316
Try
var html = '<pre class = "classy"> text </pre>';
var a = $(html);
a.filter('.classy').each( function (i, x) {
$(x).wrapInner('<h1></h1>');
})
Here the variable a
will have the intended content <pre class = "classy"> <h1> text </h1> </pre>
.
Demo: Fiddle
Under the given values it can be even simplified as
var a = $(html);
a.each( function (i, x) {
$(x).wrapInner('<h1></h1>');
})
Demo: Fiddle
Note: If you want contents of a
as a html string
var html = $('<div>').append(a.clone()).html();
Demo: Fiddle
Upvotes: 2