简体   繁体   中英

using the html code in the javascript

<body>
     <script type="text/javascript">
         var a="sreedhar";
         <input type="text" value="abc">
     </script>
</body>

It gives the syntax error. can't we use "html tags" directly in "javascript".

No, you can't use them directly in JavaScript.

However you may treat them as strings:

var str = '<input type="text" value="abc">';

or as DOM elements:

var input = document.createElement('input');
input.type = 'text';
input.value = 'abc';

And then append to the markup, eg document.body.appendChild(input); .

Usually a well formated hmtl with javascript looks like this.

<HTML>
<HEAD>
        <script type="text/javascript">
              var a="sreedhar";
        </script>
</HEAD>    
<BODY>
        <input type="text" value="abc">
</BODY>
</HTML>

If you want to generate some html with javascript then assign it as a string to some variable.

For example you have a div having id='abc' and you want to generate a textbox in this div then you need to do like this

  <script type="text/javascript">
   var textbox = '<input type="text" value="abc">';
   $('#abc').append(textbox);
  </script>

Maybe you want this:

<script type="text/javascript">
var a="sreedhar";
document.write('<input type="text" value="abc">');
</script>
</BODY>
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
     //put javascript function here

  </script> 
 </head>

 <body>
     <input type="text" value="abc">
 </body>
</html>

You can use html element inside the javascript using element id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM