Categories
JavaScript Answers

How to Get the Indexes of Child Nodes with JavaScript?

Sometimes, we want to get the indexes of child nodes with JavaScript.

In this article, we’ll look at how to get the indexes of child nodes with JavaScript.

Use the Array.from Method

We can use the Array.from method to convert the node list object with the list of selected elements to an array.

Then we can use the array to get the index of the element.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

Then we can get the divs and the indexes of them by writing:

const divs = document.querySelectorAll('div')
const arr = Array.from(divs)
for (const [index, div] of arr.entries()) {
  console.log(index, div)
}

We call document.querySelectorAll with the div.

Then we call Array.from with divs to convert the node list to an array.

Next, use the for-of loop with arr.entries to return an array with the arrays of the index of each div and the div object itself.

index has the index, and div has the div.

Use the Spread Operator

Another way to convert the node list into an array is to use the spread operator.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

Then we can write:

const divs = document.querySelectorAll('div')
const arr = [...divs]
for (const [index, div] of arr.entries()) {
  console.log(index, div)
}

And we get the same result as before.

We just replaced Array.from with the spread operator.

Conclusion

To get the indexes of child elements with JavaScript, we convert the node list with the selected elements into an array.

Categories
JavaScript Answers

How to Create a Link Using JavaScript?

Sometimes, we want to create a link with JavaScript.

In this article, we’ll look at how to create a link with JavaScript.

Use the document.createElement Method

We can use the document.createElement method to create an anchor element.

For instance,. we can write:

const a = document.createElement('a');
a.setAttribute('href', 'http://example.com');
a.innerHTML = 'example';
document.body.appendChild(a);

We call document.createElement with 'a' to create an anchor element.

Then we call setAttribute with 'href' and the value of the href attribute to set the URL that the link goes to.

Next, we set the innerHTML property to set the text content of the link.

And finally, we call document.body.appendChild to append the a link to the body.

Set the document.body.innerHTML Property

Another way to add a link to the document body is to set the innerHTML property to the HTML content we want to show.

For instance, we can write:

document.body.innerHTML = `<a href="http://example.com">example</a>`;

to set the innerHTML property top a string with the code for the anchor element.

Conclusion

We can create a link with the document.createElement method or setting the innerHTML property of the element that we want the link to be in.

Categories
JavaScript Answers

How to Insert Text into the Text Area at the Current Cursor Position?

Sometimes, we want to insert text into a text area at the current cursor position.

In this article, we’ll look at how to insert text into the text area at the current cursor position.

Use the setRangeText Method

We can use the setRangeText method to add text at the current cursor position.

For instance, if we have the following input:

<input id="input"/>

Then we can write the following JavaScript code to add the text at the cursor position when we press the Enter key when the cursor is in the input:

const typeInTextarea = (newText, el = document.activeElement) => {
  const [start, end] = [el.selectionStart, el.selectionEnd];
  el.setRangeText(newText, start, end, 'select');
}

document.getElementById("input").onkeydown = e => {
  if (e.key === "Enter") {
    typeInTextarea("abc");
  }
}

We create the typeInTextarea function that has the newText parameter with the text we want to insert.

And it has the el element that has the element we want to insert the text to.

document.activeElement is the current element that’s focused on.

In the function, we get the selection start and selection end with selectionStart and selectionEnd .

Then we call setRangeText with the newText , start , end and 'selection' to add the newText at the current cursor position.

Then we have the onkeydown property set to a function that calls the typeInTextarea function with the text we want to insert with the enter key is pressed.

Conclusion

We can insert text into an input at the cursor position when we press a key with the setRangeText method.

Categories
JavaScript Answers

How to Set the Cursor Position on contentEditable Div with JavaScript?

Sometimes, we want to set the cursor position on a contenteditable div with JavaScript.

In this article, we’ll look at how to set the cursor position on a contenteditable div with JavaScript.

Use the document.creatRange Method

We can use the document.createRange method to create the selection range.

Then we can call addRange on the returned selection object to select the content.

For instance, if we have the following HTML:

<div id="selectable" contenteditable>http://example.com/page.htm</div>

Then we can put a cursor on it by writing:

const el = document.getElementById('selectable');  
const selection = window.getSelection();  
const range = document.createRange();  
selection.removeAllRanges();  
range.selectNodeContents(el);  
range.collapse(false);  
selection.addRange(range);  
el.focus();

We get the div with getElementById .

Then we call window.getSelection to create a selection.

Then we call document.createRange to create the selection range.

Next, we call removeAllRanges to remove any existing selection.

Then we call selectNodeContents with el to apply the selection to the div.

And then we call addRange to select the content.

Finally, we call el.focus() to focus on the element to add the cursor.

Now we should see the cursor at the end of the text.

Conclusion

We can set the cursor position on a contenteditable div with JavaScript browser document.createRange method.

Categories
JavaScript Answers

How to Select All Div Text with a Single Mouse Click with JavaScript?

Sometimes, we want to select all div text with a single mouse click with JavaScript.

In this article, we’ll look at how to select all div text with a single mouse click with JavaScript.

Use the document.body.createTextRange or document.createRange Method

We can use the document.body.createTextRange or document.createRange method to create a selection.

For instance, if we have the following HTML:

<div id="selectable">http://example.com/page.htm</div>

Then we can write the following code:

const selectable = document.getElementById('selectable')  
selectable.addEventListener('click', () => {  
  if (document.selection) {   
    const range = document.body.createTextRange();  
    range.moveToElementText(selectable);  
    range.select();  
  } else if (window.getSelection) {  
    const range = document.createRange();  
    range.selectNode(selectable);  
    window.getSelection().removeAllRanges();  
    window.getSelection().addRange(range);  
  }  
})

to add a click listener to the div and select the text in the div when we click on it.

To do this, we call getElementById to select the div.

Then we call addEventListener with 'click' to add a click listener to it.

In the callback, we call documebnt.create.createTextRange method to create a selection if document.selection is defined.

This is defined if the code is run in IE.

Then we call moveToElementText to move the cursor to the text content.

Then we call select to highlight all the text.

On all other browsers, we call document.createRange to create the selection.

Then we call selectNode with the element with the content that we want to create the selection.

Then we call removeAllRanges to remove all the existing selected items.

And finally, we call addRange with the range to select the selection range we created.

Now when we click on the div text, the text will be selected.

Conclusion

We can select all the text when we click on the div text by creating a selection object and then select the text.