Merbin Joe
Merbin Joe

Reputation: 688

Store html code to javascript variable

I have a problem when converting store html code to javascript variable, I know we can convert using converter tools, but I can't use this converter in my situation.

I am trying the following code

var t_cls="font-effect-anaglyph rotator";
var randompostsurl="www.allinworld99.blogspot.com";
var randompoststitle="Open Inspect Element And see the Code";
var default_script = "<script> document.write('<div><a  class="+t_cls+" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>'); <\/script>\n";

$("#apnd").append(default_script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<div id="apnd"></div>

The above one will produce the following output

<a class="font-effect-anaglyph" rotator="" href="www.allinworld99.blogspot.com" rel="nofollow">Open Inspect Element And see the Code</a>

Why the rotator class will created as new attribute?

Upvotes: 1

Views: 2486

Answers (3)

blin2linkme
blin2linkme

Reputation: 119

As there are no quotes in class, it produce rotator as a new attribute. But you can achieve rotator as a class by the following way. i.e replacing single quotes with escape sequence.

<script>$(document).ready(function(){
 var t_cls="font-effect-anaglyph rotator", randompostsurl="www.allinworld99.blogspot.com",
 randompoststitle="Open Inspect Element And see the Code",
 default_script = "document.write(\"<div><a class=\""+t_cls+"\" href=\"" + randompostsurl + "\" rel=\"nofollow\">\" + randompoststitle + \"<\/a><\/div>\");<\/script>\n";
$("#apnd").append(default_script);
});
</script>

Upvotes: 0

Amit
Amit

Reputation: 847

Replace your default_script code

 default_script = "<script>        document.write('<div><a class='"+t_cls+"' href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

Because there are no quotes around the class attribute in the result. You need to add them, since you have a space in the attribute's value:

default_script = "<script>        document.write('<div><a class=\""+t_cls+"\" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";
// Here --------------------------------------------------------^^---------^^

Upvotes: 4

Related Questions