Categories
JavaScript Answers

How to Remove Multiple Elements from an Array in JavaScript?

One way to remove multiple elements from a JavaScript array is to use a for -of loop.

For instance, we can write:

const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
  removeValFromIndex = [0, 2, 4];

for (const i of removeValFromIndex.reverse()) {
  valuesArr.splice(i, 1);
}
console.log(valuesArr)

We have the valuesArr with the items we want to remove.

removeValFromIndex has the indexes with the indexes of valuesArr that we want to remove.

Then we loop through the removeValFromIndex backwards with reverse and the for-of loop and remove each item with splice .

We’ve to loop backwards so that we won’t mess up the indexes for items that are yet to be removed.

Therefore, valuesArr is [“v2”, “v4”] .

Use Array.prototype.filter

Also, we can use the JavaScript array filter method to remove items from the array given the indexes of the items we want to remove.

For instance, we can write:

const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
  removeValFromIndex = [0, 2, 4];

const filtered = valuesArr.filter((value, index) => {
  return !removeValFromIndex.includes(index);
})
console.log(filtered)

We call filter with a callback that has the index parameter as the 2nd parameter.

Then we call includes with index to see if the index isn’t in removeValFromIndex .

If it’s not, then we keep the item with the given index in the returned array.

Therefore, filtered is [“v2”, “v4”] .

Categories
JavaScript Answers

How to Get the Caret Index Position of a contentEditable Element with JavaScript?

We can use the document.getSelector to get the selection.

And then we can use that to get the length of the selection to get the cursor position.

For instance, we can write the following HTML:

<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>

Then we can write the following JavaScript code to get the location of the cursor by writing:

const cursorPosition = () => {
  const sel = document.getSelection();
  sel.modify("extend", "backward", "paragraphboundary");
  const pos = sel.toString().length;
  if (sel.anchorNode != undefined) sel.collapseToEnd();
  return pos;
}

const elm = document.querySelector('[contenteditable]');

const printCaretPosition = () => {
  console.log(cursorPosition(), 'length:', elm.textContent.trim().length)
}
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)

We have the cursorPosition function that calls the documebnt.getSelection method to get the text inside the div.

Then we call modify to adjust the current selection.

We move 'backward' by 'paragraphboundary' .

Then we get the length of the selection after converting it to a string.

And then we collapse the selection and return pos to return the position of the cursor.

Next, we get the div with querySelector .

And then we create the printCaretPosition to print the cursor position.

Finally, we call addEventListener so that we call printCaretPosition when we click or type on the div.

Categories
JavaScript Answers

How to Disable Scrolling on Number Input with JavaScript?

We can listen to the wheel event and remove focus on the input when we start scrolling on the mouse wheel.

For instance, if we have the following HTML:

<input type='number'>

Then we can listen to the wheel event by writing:

document.addEventListener("wheel", (event) => {  
  if (document.activeElement.type === "number") {  
    document.activeElement.blur();  
  }  
});

We check if the type attribute of the element we focused on is set to number with:

document.activeElement.type === "number"

If it is, then we call document.activeElement.blur() to remove focus from it.

Now when we try to scroll with the scroll wheel, the browser will move focus away from the input.

Categories
JavaScript Answers

How to Use querySelectorAll to Select Elements that Have a Specific Attribute Set?

We can use selectors for selecting elements with specific attributes.

For instance, if we have the following HTML:

<input type='checkbox' value='apple'> apple
<input type='checkbox' value='orange'> orange
<input type='radio' value='grape'> grape

Then we can select all the checkboxes that have a value attribute set by writing:

const inputs = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
console.log(inputs)

input gets all the input elements

[value] narrows down to inputs with the value attribute set.

[type=”checkbox”] means we get the inputs with type attribute set to checkbox .

And :not([value=””] means we get the inputs with value not set to an empty string.

Therefore, inputs should be the checkboxes in the HTML.

Categories
JavaScript Answers

How to Append a JavaScript String to the DOM?

We can call appendChild on a DOM node to append a child node to a given DOM node.

For instance, if we have the given div:

<div id='test'>  
  foo  
</div>

Then we can append another div as a child of the div above with appendChild .

To do this, we write:

const child = document.createElement('div');  
child.innerHTML = 'bar';  
const {  
  firstChild  
} = child;  
document.getElementById('test').appendChild(firstChild);

We call documenbt.createElement to creat the child div element.

Then we set its innerHTML to the content we want inside the div.

Next, we get the firstChild from child .

And then we call appendChild on the div with ID test with firstChild to append it as another child node of the div with ID test .

Now we see ‘foo bar’ is displayed.

Append a String to the innerHTML Value

We can also just append a string to the innerHTML directly.

So if we have:

<div id='test'>  
  foo  
</div>

Then we can use the += operator to append a string into the div with ID test by writing:

document.getElementById('test').innerHTML += ' bar'

And we get the same result as the previous example.