Categories
JavaScript Answers

How to add “href” attribute to a link dynamically using JavaScript?

To add "href" attribute to a link dynamically using JavaScript, we call the setAttribute method.

For instance, we write

const a = document.getElementById("link");
a.setAttribute("href", url);

to select the link with getElementById.

Then we call setAttribute to set the href attribute value to url.

Categories
JavaScript Answers

How to paste as plain text with JavaScript execCommand?

To paste as plain text with JavaScript execCommand, we get the pasted data as plain text before we insert it.

For instance, we write

editor.addEventListener("paste", (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData("text/plain");
  document.execCommand("insertHTML", false, text);
});

to listen to the past event on editor with addEventListener.

In it, we call preventDefault to stop the default paste behavior.

Then we get the pasted text as plain text by calling clipboardData.getData with 'text/plain',

Finally, we call execCommand to insert the text into editor.

Categories
JavaScript Answers

How to play a notification sound on websites with JavaScript?

To play a notification sound on websites with JavaScript, we call the play method.

For instance, we write

const audio = new Audio(url);
audio.play();

to create an audio element with the audio url with the Audio constructor.

Then we call play to play the clip.

Categories
JavaScript Answers

How to click on element with text in Puppeteer and JavaScript?

To click on element with text in Puppeteer and JavaScript, we call the click method.

For instance, we write

const [button] = await page.$x("//button[contains(., 'Button text')]");
await button?.click();

to get the buttons with the ‘Button text’ text with the page.$x method.

We destructure the array to get the first one.

Then we call click on the first button to click on the button.

Categories
JavaScript Answers

How to delete all rows in an HTML table with JavaScript?

To delete all rows in an HTML table with JavaScript, we use the remove method.

For instance, we write

document.querySelectorAll("table tbody tr").forEach((e) => {
  e.remove();
});

to select all tr elements with querySelectorAll.

Then we call forEach with a callback to call remove to remove each tr element.