How to interact JavaScript + jQuery with CSS

3

I have a class in CSS that is called .codigo . I wanted when I was using it, it would remove the HTML formatting (example: make <font></font> appear the same is appearing here in the PT SO, using the .text() method) and leave the span of the same style specified by the class. How do I interact with JS, jQuery and CSS?

    
asked by anonymous 11.02.2014 / 18:19

2 answers

5

With jQuery and CSS, you can retrieve HTML and set that content as text:

$('.classe').text($('.classe').html())

And then set a CSS for the font to get the correct spacing:

.classe {
    display: block;
    font-family: monospace;
    white-space: pre;
}

See the example in jsfiddle .

However, I advise against using this scheme as it may suffer an attack of XSS in case of displaying content user. Ideally you would make an HTML escape on the server side.

Update

Without Javascript, you could place the HTML inside a <textarea> or replace the special HTML characters on the server:

Examples:

<textarea>Código   <strong>html</strong> aqui!</textarea>
<pre>Código   &lt;strong&gt;html&lt;/strong&gt; aqui!</pre>

See the jsfiddle of this example .

One way to replace characters using php is to htmlentities .

Note that textarea is also vulnerable to Cross Site Scripting , for example if a user can write a value like the following:

</textarea><script>....</script><textarea>
    
11.02.2014 / 18:33
1

If you want to add your formatting to a specific tag of your HTML, it would look something like this:

$(document).ready(function () {
    $('font').addClass('codigo');
});

This will add your code class to all font tag after loading.

But you can achieve the same result by modifying your CSS like this:

.codigo, font {
    /* meu estilo */
}

In case the comma indicates that the same rules that apply to class .codigo will apply to all elements <font> of your page.

    
11.02.2014 / 18:29