1

I have a string with HTML from the website like:

\n
<div>
\t<div>
...
\t</div>
</div>

If I construct a jquery from this by:

$(tmpl)   // like $("\n<div>")

It will give me error saying "unrecognized expression:<div> <div> </div></div>".

I tried using $(tmpl.replace(/[\t\r\n]/,"")). It works but does not seem natural to me. I also tried using $('body').append(tmpl); it does not require a replace but I want to change the attr/styles/data before I attach it to DOM. If I attach it first, I will need to select it again.

Is there any way to create a jquery object from this type of HTML snippets without replace and before attaching it to DOM?

SwiftMango
  • 15,092
  • 13
  • 71
  • 136

1 Answers1

0

I suggest reading this answer, where a fake div is created and then referenced by a jQuery object in order to edit attr/styles/data of an html string before inserting it into the DOM. You can use JSON.stringify() to see the newlines, tabs, and carriage returns in the jQuery object and that they are preserved after inserting into the DOM. DEMO

Community
  • 1
  • 1
dnapierata
  • 1,153
  • 1
  • 16
  • 28
  • This does not help. I mentioned all this in my post already. It does not work properly when there is a leading \n or \t or spaces. – SwiftMango Feb 16 '13 at 07:07
  • You have to create a dummy div using `$('
    ')` and insert into this using `.html()`. Then you can do what you want with this object. I've updated my answer with a jsFiddle demo.
    – dnapierata Feb 16 '13 at 07:27