1

Hello I'm very new to javascript and doing my first steps I was wondering if I could style the content of a variable in the document.write instruction and I came to this.

    <!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .style1{
            background-color: chartreuse;
        }
    </style>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var name1;
        name1=prompt("Write your name");
        document.write('<p class="style1">'+name1+'</p>');
    </script>
</body>
</html>

I got that solved by reviewing some posts here the question is how does this actually work?

document.write('<p class="style1">'+name1+'</p>');

I'm not sure I understand why I need to put ' for this instruction could somebody explain that please thank you btw I'm sorry this is a very basic question but I would like to know also if you guys have some more ways to style a document.write it would be nice to know .

2
  • Please have a good understanding how CSS/Style works. Please go through developer.mozilla.org/en-US/docs/Web/CSS. Commented Aug 2, 2020 at 3:39
  • The single quote char is there so that the double quotes don't need to be escaped. Technically you dont need the single quote chars as you infer. You could use double quotes on the outside, but all your inside double quotes will need to be escaped as in \" Commented Aug 2, 2020 at 3:45

3 Answers 3

1

I'd suggest taking a slightly different approach. You can add a div to your HTML with an ID of "test" (or whatever you'd like), then edit the innerHTML of that div like so:

document.getElementById("test").innerHTML = name1;

Sign up to request clarification or add additional context in comments.

Comments

0

document.write : Write HTML elements with text directly to the HTML document

 var name1;
 name1=prompt("Write your name");
 document.write('<p class="style1">'+name1+'</p>');
  1. Create a variable named name1
  2. Give a value to name1 variable from user input in prompt alert
  3. Write p element with class style1 and its content is value from name1 to HTML document

Comments

0

document.write(); is writing a text in your HTML File. so if you write like this:

<script>document.write("<p>blah</p>");</script>

then you are writing html Source like <p>blah</p>.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.