Categories
JavaScript Answers

How to get the pure text without HTML element using JavaScript?

To get the pure text without HTML element using JavaScript, we can use the textContent property.

For instance, we write

const element = document.getElementById("txt");
const text = element.textContent;

to select the element with getElementById.

And then we get the textContent property to get the pure text inside the element.

Categories
JavaScript Answers

How to submit a form with JavaScript by clicking a link?

To submit a form with JavaScript by clicking a link, we can add a button and attach a click listener to it.

For instance, we write

<form id="form-id">
  <button id="your-id">submit</button>
</form>

to add a form.

Then we write

const form = document.getElementById("form-id");

document.getElementById("your-id").addEventListener("click", () => {
  form.submit();
});

to select the form with getElementById.

And then we select the button with getElementById and add a click listener to it with addEventListener.

In the click listener, we call form.submit to submit the form.

Categories
JavaScript Answers

How to detect which one of the defined font was used in a web page with JavaScript?

To detect which one of the defined font was used in a web page with JavaScript, we use the font property.

For instance, we write

const font = document.getElementById("header").style.font;

to select the element with getElementById.

And then we get the font used with the style.font property.

Categories
JavaScript Answers

How to count text lines inside an DOM element with JavaScript?

To count text lines inside an DOM element with JavaScript, we can calculate it from the element height and its line height.

For instance, we write

const el = document.getElementById("content");
const divHeight = el.offsetHeight;
const lineHeight = parseInt(el.style.lineHeight);
const lines = divHeight / lineHeight;
console.log(lines);

to get the element with getElementById.

We get its height with offsetHeight.

We get its line height with el.style.lineHeight.

Then we divide divHeight by lineHeight to get the number of lines.

Categories
JavaScript Answers

How to fix “Uncaught TypeError: Illegal invocation” in Chrome and JavaScript?

To fix "Uncaught TypeError: Illegal invocation" in Chrome and JavaScript, we should make sure we’re calling a function.

For instance, we write

const obj = {
  someProperty: true,
  someMethod() {
    console.log(this.someProperty);
  },
};
obj.someMethod();

to define the obj with the someMethod method.

Then we call it with obj.someMethod();.

It logs true since this is the obj object.