with jquery http://jsfiddle.net/JamesKyle/L4b8b/ I am trying to make an extremel...">

How to make a simple print <pre class = "prettyprint-override"> with jquery

http://jsfiddle.net/JamesKyle/L4b8b/

I am trying to make an extremely simple fingerprint function using jQuery, but I don't know how to find elements, attributes and values โ€‹โ€‹(shown in jsfiddle).

I am trying to do the following:

  • Wrap elements with <span class="element" />
  • Wrap attributes with <span class="attribute" />
  • Replace values โ€‹โ€‹with <span class="value" />
  • Replace < with <
  • Replace > with >

Here is the current jQuery that I have:

 $(document).ready(function() { $('pre.prettyprint').each(function() { $(this).css('whitespace','pre-line'); /* Why isnt ^this^ working? */ var code = $(this).html(); // How should I define the following var element = $(code).find(/* ELEMENTS */); var attribute = $(code).find(/* ATTRIBUTES */); var value = $(code).find(/* Values */); $(element).wrap('<span class="element" />'); $(attribute).wrap('<span class="attribute" />'); $(value).wrap('<span class="value" />'); $(code).find('<').replaceWith('&lt'); $(code).find('>').replaceWith('&gt'); }); }); 

What is trying to format this:

 <pre class="prettyprint"> <a href="http://website.com">Visit Website</a> <a href="#top">Back to Top</a> </pre> 

in it:

 <pre class="prettyprint"> <span class="element">a <span class="attribute">href</span>=<span class="value">"http://website.com"</span></span>Visit Website<span class="element">/a</span> <br/> <span class="element">a <span class="attribute">href</span>=<span class="value">"#top"</span></span>Back to Top<span class="element">/a</span> </pre> 

Thank you ahead of time!

Here you can see jsfiddle: http://jsfiddle.net/JamesKyle/L4b8b/

+6
source share
3 answers

Real magic would come about when processing a tag of arbitrary properties. Here's a simple "anchor" version: jsFiddle

 $('pre.prettyprint').each(function() { $('a').each(function(){ $anchor = $(this); html = '<span class="element">&lt;a '; html += '<span class="attribute">href</span>=<span class="value">"' + $anchor.attr('href') + '"&gt;</span>'; html += '</span>' + $anchor.text() + '<span class="element">&lt;/a&gt;</span>' $anchor.replaceWith(html); }); }); 
+2
source

I donโ€™t know how to do it with jQuery, and no one else does it because it is not as easy as you do it. Luckily for you, someone has already written a bad printable solution in JavaScript for markup:

http://prettydiff.com/markup_beauty.js

As far as I know, this is the most comprehensive beautiful printing algorithm for markup languages โ€‹โ€‹ever written.

+2
source

To be honest, you wonโ€™t be able to wrap elements and attributes as you want with .find() . The easiest way to achieve what you want is to use a regular expression to determine what needs to be wrapped and applied. Of course, this is much easier said than done.

0
source

Source: https://habr.com/ru/post/902810/


All Articles