0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.