select not input elements text JS
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.
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.
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.
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.