Error caused by line break in append

Asked

Viewed 967 times

1

In jquery, if I insert the following code, error ::

variavel.append('<div class="qualquer">
                    <div class="subdivs">
                        conteudo da subdiv
                    </div>
                    <div class="subdivs">
                        conteudo da subdiv
                    </div>
                </div>
                    ');

But if I put the same code without line break, no more error ::

variavel.append('<div class="qualquer"><div class="subdivs">conteudo da subdiv</div><div class="subdivs">conteudo da subdiv</div></div>');

My doubt is

How to avoid this line break error? There is a "substitute" pro append so I can insert the line break code?

NOTE: I’m trying to learn more about Jquery so I don’t know the means to accomplish such a thing!

2 answers

1


The problem occurs due to line breaks that prevent the formation of string, which is the argument accepted by append() of jQuery. You can solve this using \ at the end of each line, in which case you will need to change your double quotes (") by simple (') in the internal contents as below:

variavel.append("<div class='qualquer'> \
                    <div class='subdivs'> \
                        conteudo da subdiv \
                    </div> \
                    <div class='subdivs'> \
                        conteudo da subdiv \
                    </div> \
                </div>");

outworking: "<div class='qualquer'> <div class='subdivs'> conteudo da subdiv </div> <div class='subdivs'> conteudo da subdiv </div> </div>"

Or you can also divide by lines, and concatenate one by one using character (+) as the example below:

variavel.append('<div class="qualquer">' +
                    '<div class="subdivs">' +
                        'conteudo da subdiv' +
                    '</div>' +
                    '<div class="subdivs">' +
                        'conteudo da subdiv' +
                    '</div>' +
                '</div>');

outworking: "<div class="qualquer"><div class="subdivs">conteudo da subdiv</div><div class="subdivs">conteudo da subdiv</div></div>"

The difference between the two is that the first inserts half columns at the end of each row, while the second concatenates directly. Remembering that both can be added to a variable and you can set the same in your append().

  • Interesting. The solution is simpler than I could imagine!

  • edited the post explaining the problem, for a better intention :)

0

You can use the n:

$('#teste').append('<div class="qualquer">\n<div class="subdivs">\nconteudo da subdiv\n</div>\n<div class="subdivs">\nconteudo da subdiv\n</div>\n</div>');

https://jsfiddle.net/uv3nqemj/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.