- 05 Sep 2024
- 1 Minute zum Lesen
-
Drucken
-
DunkelLicht
-
pdf
Capture the Text of an Element using innerText()
- Aktualisiert am 05 Sep 2024
- 1 Minute zum Lesen
-
Drucken
-
DunkelLicht
-
pdf
What is innerText and textContent?
In JavaScript, innerText
and textContent
are two properties that are used to access and modify the text content of an element on a web page. By default, when you select an element using Whatfix, the element text is captured using textContent().
Here are some key differences between the two:
innerText | textContent |
---|---|
Retrieves the visible text content of an element. | Retrieves the content of an element, including all text and nested elements. |
Excludes text that is hidden with CSS or rendered invisible due to its parent’s visibility settings. | Ignores the style or visibility of the element. |
Returns the formatted and styled text content. | Returns the raw text content as a string. |
For example, consider the following code snippet:
<div id="test">
Hello <span style="display: none;">world</span>!
</div>
let element = document.getElementById("example");
console.log(element.textContent); // Output: Hello world!
console.log(element.innerText); // Output: Hello !
In this snippet, the element with the ID test contains a hidden element with the text world. Here's how the output varies:
- element.textContent outputs “Hello world!” (including the hidden text).
- element.innerText outputs “Hello!” (excluding the hidden text).
Why should I override Text Content with Inner Text?
When Override Text Content with Inner text is enabled, instead of capturing the textContent property of selected elements, Whatfix captures the innerText property. Here’s why:
- Visibility: By using innerText, only the text content visible to the user on the screen is captured.
- Hidden Elements: Certain text elements may be hidden or styled in a way that makes them invisible to the user. Despite this, they are still captured by the textContent property. Using innerText ensures accuracy.
Use the following steps to override textContent with innerText:
-
On the Whatfix Guidance dashboard, click Settings.
-
Click Advanced customisation.
-
Click Technical configuration.
-
Click Add preferences.
-
Click Common Properties.
-
Select the Override text content with inner text checkbox.
-
Click Add.
-
Enable the Override text content with inner text toggle.
-
Click Save.