Can't get the text content from Headings nor Parahgraph

Hello,

I have been reviewing the documentation on String Elements, which mentions that one can retrieve the content of the elements. However, when I attempt to use .getText(), I encounter an error indicating that this function does not exist on the element type.

Upon checking all available methods and keys for String Elements, I found the following list:

[
    "id", "detach", "destroy", "configurable", "save", "customAttributes",
    "getCustomAttribute", "setCustomAttribute", "getAllCustomAttributes",
    "removeCustomAttribute", "domId", "getDomId", "setDomId", "styles",
    "getStyles", "setStyles", "children", "getChildren", "setChildren",
    "textContent", "setTextContent", "type", "plugin", "constructor",
    "__defineGetter__", "__defineSetter__", "hasOwnProperty",
    "__lookupGetter__", "__lookupSetter__", "isPrototypeOf",
    "propertyIsEnumerable", "toString", "valueOf", "__proto__",
    "toLocaleString"
]

It appears that the .getText() function is not included in this list, despite being mentioned in the documentation. Has anyone else encountered this discrepancy?

Clarification: I’m selecting the current element and I’m trying to call the method to that, so on a text element.

Here a code example:

const element  = await webflow.getSelectedElement()

if(element.textContent) {
  const text = element.getText() // throws function is not found error
  console.log(text)
}

The docs look like a work in progress.
I’d try a few approaches-

First there is a setTextContent on DOMElements, so you might try getTextContent to see if it’s simply absent from the documentation.

If that doesn’t work, inspect element.getChildren() to see if it has children, if so that’s likely where you’ll find your string element and be able to use textContent on that.

Hey @az_ben,

Try the following:

const element  = await webflow.getSelectedElement()

if(element.textContent) {
  const textChild = element.getChildren()
  const text = textChild[0].getText()

  console.log(text)
}

Let me know how that goes!

1 Like

Hi, I’ve got the same problem. Cannot get the current text from a selected element.
When trying your suggested code, I get the error saying getChildren doesn’t exist on the element.
Any other suggestions? A simple getTextContent function would have been nice here.

I’ve tried to get the DOM element by the data-w-id attribute, but that probably doesn’t work because the actual element is nested inside an iframe, and the app is not part of that iframe.

Grts,

Peter

Hey @Peter_Datapad, thanks for the follow up!

One of our engineers has shared the below which may work:

const getTextContent = async (el) => {
  if (el.type === 'String') return await el.getText() || ''
  if (!el.children) return ''
  const children = await el.getChildren()

  let text = ''

  for (const child of children) {
    text += await getTextContent(child)
  }

  return text
}