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.

Categories
JavaScript Answers

How to Insert a Row in an HTML Table Body in JavaScript?

Sometimes, we want to insert a row in an HTML table body with JavaScript.

In this article, we’ll look at how to insert a row in an HTML table body with JavaScript.

Call the insertRow and insertCell Methods

JavaScript DOM API has the insertRow method built into the tbody element.

And it also has the insertCell method built into the tr element.

insertRow lets us insert a new table row.

And insertCell method lets us insert a new cell into a table row.

For instance, if we have the following HTML:

<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>aaaaa</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My footer</td>
    </tr>
  </tfoot>
</table>

We can write:

const tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

const newRow = tbodyRef.insertRow();
const newCell = newRow.insertCell();
const newText = document.createTextNode('new row');
newCell.appendChild(newText);

We have a table, with the tbody element inside.

Then to get the tbody , we call getElementId to get the table.

Then we call getElementsByTagName to get the tbody element.

Next, we call insertRow on the tbody element to create a new tr.

And then we call insertRow on the newly created tr .

Next, we call document.createTextNode to create a new text node for the table cell content.

And then we call newCell.appendChild to append the newText text node.

Now we should see ‘new row’ before the footer.

Conclusion

We can use methods built into tbody and tr DOM objects to insert new table rows and cells with JavaScript.