-3

I have dynamically created a href in js file.

I have to trigger the <a href> from the js file and the link is not present in the HTML part. But unable to trigger the link.

let content = <a href='www.google.com'></a>;

I have to trigger the above statement from js.

NB: I can't use jquery

2
  • 1
    Without more context, we won't be able to help you. Can you please include all the relevant template and JavaScript code? You can edit your question to include more code. What you're trying to do is generally possible in LWC, but we don't have enough information to help right now.
    – sfdcfox
    May 16 at 14:15
  • I formed a <a href='www.google.com'></a> tag in js file (let content = <a href='www.google.com'></a>); but I can't show it in html part. How can I trigger the <a href> tag from js page? May 20 at 5:43

1 Answer 1

1

You just need to use innerHTML.

import { LightningElement } from "lwc";

export default class App extends LightningElement {
  renderedCallback() {
    const content = '<a href="https://www.google.com/">Google</a>';
    this.template.querySelector('div').innerHTML = content;
  }
}

Or, if you mean to say you want to redirect to a website:

window.location.href = 'https://www.google.com/';

Or, if you want to trigger a download:

const a = document.createElement('a');
a.href = 'https://www.google.com';
document.body.appendChild(a); // Firefox apparently requires this
a.click();
document.body.removeChild(a);

Note that this demo won't work entirely right because of sandboxing, but you should see the effect demonstrated.

Demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.