Categories
JavaScript Answers

How to add/remove several classes in one single instruction with classList and JavaScript?

To add/remove several classes in one single instruction with classList and JavaScript, we can call add or remove with all the classes we want to add or remove.

For instance, we write

elem.classList.add("first", "second", "third");

to call elem.classList.add to add the first, second, and third classes.

Likewise, we write

elem.classList.remove("first", "second", "third");

to call elem.classList.remove to remove the first, second, and third classes.

Categories
JavaScript Answers

How to get the values of data attributes in JavaScript?

To get the values of data attributes in JavaScript, we use the dataset property of the element.

For instance, we write

const id = document.querySelector("html").dataset.pbUserId;

to select the html element with querySelector.

And then we use the dataset property to get the value of the data-pbUserId attribute of the element.

Categories
JavaScript Answers

How to change div content with JavaScript?

To change div content with JavaScript, we set the div’s innerHTML property.

For instance, we write

document.getElementById("content").innerHTML = "whatever";

to select the div with getElementById.

And then we set its innerHTML property to the content of it.

Categories
JavaScript Answers

How to convert HTML string into DOM elements with JavaScript?

To convert HTML string into DOM elements with JavaScript, we use the DOMParser constructor.

For instance, we write

const xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
const doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML);

to create a DOMParser object and call the parseFromString method with the xmLString and the MIME type.

Then we get the first child element’s HTML code with doc.firstChild.innerHTML.

Categories
JavaScript Answers

How to get cursor position (in characters) within a text Input field with JavaScript?

To get cursor position (in characters) within a text Input field with JavaScript, we use the selectionStart method.

For instance, we write

<input type="text" id="t1" value="abcd" />
<button onclick="onClick(document.getElementById('t1'))">check position</button>

to add an input and a button.

Then button calls the onClick function when we click on the element with the input as its argument.

Next we write

function onClick(el) {
  const val = el.value;
  console.log(val.slice(0, el.selectionStart).length);
}

to define the onClick function.

In it, we get the input’s value with el.value.

And then we get the cursor position with el.selectionStart.

We call slice to get the part of the val string between index 0 and el.selectionStart - 1.