How can get the text of a div tag using only javascript (no jQuery)
Fetch the text from a div
using textContent
to retrieve unformatted text:
If you need text as shown on a webpage, employ innerText
:
Both offer efficient tools to access a div
's text with raw JavaScript.
Distinguishing between textContent
and innerText
When it's about extracting the text inside a div
, two primary suspects come to the scene: textContent
and innerText
. They might seem partners, but they have clear differences in their operations and use cases.
The 'text content' suspect
textContent
returns everything inside an element - even script and style elements, no matter whether they are visually appearing or hidden with CSS. It is the raw truth, ignoring styling or visibility modifications.
'inner text' on the surface
In contrast, innerText
respects CSS styles and visibility. So, it returns only the ‘visible’ text or the one that appears to the users after applying all the styles.
Making the right move
Use textContent
for the unfiltered truth (raw text), and innerText
for “what you see is what you get”(rendered text). Since textContent
doesn't deal with CSS, it's leaner and faster.
Support for old-age browsers
If your user base includes aging browsers not understanding textContent
, use innerText
as a backup. Here’s how you play safe:
Picking between document.getElementById
and document.querySelector
Pinpointing with getElementById
Use getElementById
to pinpoint the div by its ID when you know the target:
Aiming wide with querySelector
The document.querySelector
gives you an aiming scope. You can hit your target using any valid CSS selector:
Keeping common pitfalls at bay
Say no to innerHTML
for pure text
innerHTML
tempts by returning all the HTML content, even tags, but it might lead to security issues if dealing with untrusted content.
Value is not the right tool here
Shun value
when dealing with non-input elements. value
fits better for form input elements.
Don't be a security guard off guard
Your first job is to ensure security while handling element content. textContent
is intrinsically safer as it doesn't interpret the content as HTML. But if you're using innerHTML
, make sure to sanitize the content and keep XSS attacks at bay!
Was this article helpful?