A href in innerHTML [closed]
Asked Answered
T

2

3

I am trying to make when a href in innerHTML, but I got error or it is not working. I want to make a data from API, which can be clicked instead copy and put it into browser. When I tried the code, it will become +item.title instead go to the link that i get data from My API.

<html>
  <head>
    <title>JSON/Atom Custom Search API Example</title>
  </head>
  <body>
    <div id="content"></div>
    
    <script>
      function hndlr(response) {
      for (var i = 0; i < response.items.length; i++) {
        var item = response.items[i];
        // in production code, item.htmlTitle should have the HTML entities escaped.
        document.getElementById("content").innerHTML +="<br>"+ item.title + "<br>"   +"<a href='+item.title'>Google</a>" ;
        
      }
    }
    </script>
    <script src="https://www.googleapis.com/customsearch/v1?q=query&cx=004123968310343535430%3Aaxml6iel9yo&key=AIzaSyDxPcphnrcN9_dfkRkFTbwkv44m1-HI1Hg&callback=hndlr">
    </script>
  </body>
</html>
Trost answered 21/4, 2017 at 9:36 Comment(1)
Owh it works, i try using '" finally i know only + at the back.. Thanks alot guyzTrost
R
4

You are doing wrong concatenation, Where you assigning the innerHTML to content. It should be :

document.getElementById("content").innerHTML +="<br>"+ item.title + "<br>" +"<a href='"+item.title+"'>Google</a>";

Your function should be :

function hndlr(response) {
    for (var i = 0; i < response.items.length; i++) {
        var item = response.items[i];
        // in production code, item.htmlTitle should have the HTML entities escaped.
        document.getElementById("content").innerHTML +="<br>"+ item.title + "<br>"   +"<a href='"+item.title+"'>Google</a>" ;

    }
}
Riddell answered 21/4, 2017 at 9:44 Comment(0)
M
4

Your problem is from this line +"<a href='+item.title'>Google</a>"

since your outter enclosing apostrophe is " then for you to maintain your real values of variable is for your make sure that the variables or executables are not inside that enclosing outer " .

So this should work out for you

document.getElementById("content").innerHTML +="<br>"+ item.title + "<br>"   +"<a href='"+item.title+"'>Google</a>" ;

observe the href='"+ item.title+ "'

Margret answered 21/4, 2017 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.