简体   繁体   中英

Using JavaScript's Document.write() to create a HTML link

I have an URL stored in a variable (var URL).

I thought this would work:

document.write("<a href='"+url+"'>LINK</a>");

But it isn't? Any solution??

This is exactly what I'm trying to do:

         <script>

          var url2="https://wa.me/(phonenumber)/?text=";
          var url3="<data:post.title/>";
          var url4=url2+url3;
          var url5="<a href='"+url4+"'>ORDER VIA WHATSAPP</a>";
          document.write(url5);

              </script>

(EDIT: IT'S WORKING NOW. SOLVED!)

variables are case sensitive, this should work.

document.write("<a href='"+URL+"'>LINK</a>");

Also if you really want to use vanilla js to dynamically create an html element, I would recommend avoiding document.write because of cross site scripting attacks.

var url = 'www.yoururl/cpm'
var a = document.createElement('a')
a.textContent = 'LINK'
a.href = url 
document.body.appendChild(a)

It works if you write same name

 var url="https://www.google.com.tr/" document.write("<a href='"+url+"'>LINK</a>");

This might work instead of document.write().

<html>
  <head></head>
  <body>
    <div id="Place to insert"></div>
    <script>
      var link = document.createElement('a');
      link.textContent = 'Link Title';
      link.href = Your URL;
      document.getElementById('Place to insert').appendChild(link);
    </script>
  </body>
</html>

use document.write have it is not Good beacuse it delete all the contents inside the calling element so use innerHTML or insertAdjacentHTML instead or create the link like this

 let a = document.createElement('a');
 a.href = '#';

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