Skip to content
the poor coder

select not input elements text JS

Poor Man
Published
Reading time
1 min read
On this page

Select Non-Input Elements Text using JavaScript#

As a web developer, I have faced this situation where I had to select non-input elements' text using JavaScript. It's a common task in web development, and there are multiple solutions to it. Let's explore some of them:

1. Using the document.getSelection() Method#

The document.getSelection() method is used to select text within an element. It returns a Selection object that represents the selected text.

Text
const element = document.querySelector('div');
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);

In the above code, we first select the div element using the querySelector() method. Then, we create a Range object and select the contents of the div element using the selectNodeContents() method. Finally, we add the range to the selection using the addRange() method.

2. Using the innerText Property#

The innerText property returns the text content of an element, excluding any HTML tags. We can use it to get the text content of a non-input element.

Text
const element = document.querySelector('div');
const text = element.innerText;

In the above code, we select the div element using the querySelector() method and get its text content using the innerText property.

3. Using the textContent Property#

The textContent property returns the text content of an element, including any HTML tags. We can use it to get the text content of a non-input element.

Text
const element = document.querySelector('div');
const text = element.textContent;

In the above code, we select the div element using the querySelector() method and get its text content using the textContent property.

In conclusion, there are multiple ways to select non-input elements' text using JavaScript. We can use the document.getSelection() method, the innerText property, or the textContent property depending on our requirements.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC