Home > database >  Put JavaScript value inside HTML
Put JavaScript value inside HTML

Time:10-12

How to put JavaScript value inside HTML ?

I am trying to put JavaScript value inside HTML like below.

<p>
    Check your Credit Score <a href="http://someaddress.com?first_name='  first_name  '" target="_blank">Here</a>
</p>

CodePudding user response:

do this if you want to change the link document.querySelector('a').href = "http://someaddress.com?first_name=" first_name;

CodePudding user response:

To achieve the results, you can make use of document.getElementById('').href property:

HTML (added the id attribute to the <a> tag):

<p>
  Check your Credit Score <a id="link" href="" target="_blank">Here</a>
</p>

JavaScript:

window.onload = function() {
    var first_name = 'Peter';
  document.getElementById('link').href = 'http://someaddress.com?first_name='  first_name;
  
  // debug your results
  console.log(document.getElementById('link').href);
}

Here is the JSFiddle

CodePudding user response:

You can do like this

<p>
 Check your Credit Score
<a href="http://someaddress.com?first_name='  first_name  '" target="_blank"
 >Here</a >
</p>

 <script type="text/javascript">
   const a = document.querySelector('a');

   const first_name = 'John';

   a.href = 'http://someaddress.com?first_name='   first_name ;
 
 </script>

CodePudding user response:

For best practice do an if check otherwise your selector might not be found in the dom.

Also, if in querySelector("...anything...") not querySelector("a") is given the editor won't suggest the href prop that exists or not. Hence, setAttribute makes more sense.

const URL = "http://someaddress.com?first_name="

const name = 'adiat'

const anchor = document.querySelector(".what-ever")

if(anchor){
    anchor.setAttribute("href", `${URL}${name}`);
}else{
    console.warn("element not found to replace href attribute")
}

// shorthand -> anchor?.setAttribute("href", `${URL}${name}`);

CodePudding user response:

A robust way would be to use a token to replace, I've used {{FirstName}}. Use an attribute selector to select via that token then replace that token on the href attribute

let firstNameLinks = document.querySelectorAll("a[href*='{{FirstName}}'");
let firstName = "Bob";
for(i = 0; i < firstNameLinks.length; i  ){
console.log(firstNameLinks[i].href)
  firstNameLinks[i].href  = firstNameLinks[i].href.replace("{{FirstName}}", firstName); 
}
<a href="https:someurl.com?firstName={{FirstName}}">A link</a>
<a href="https:someotherurl.com?aVariambe=false&firstName={{FirstName}}">Another link</a>

  • Related