Important: Please read the Qt Code of Conduct -

How to use getElementsByClassName with WebEngine runJavascript

  • Hello,
    I'm having a problem modifying the content of HTML document using getElementByClassName or getElementById. My code is not generating error except when there is an error in the code, but it's not working either. Here is the relevant part of my code that is not working:

    WebEngineView {
           id: webviewer
           anchors.fill: parent
           url: ""
           opacity: 1
           visible: true
    Connections {
       target: webviewer
           onLoadingChanged: {
       	if (WebEngineLoadRequest.LoadSucceededStatus)
       		webviewer.runJavaScript("var Elem = document.getElementsByClassName('highlight-span'); Elem.innerHTML = 'Hello!'";)

    But when I target a specific HTML element with 1 line of code, it works.

    webviewer.runJavascript("document.body.innerHTML = 'Hello!' ")

    Is it that runJavascript doesn't understand 2 lines of code? Or getElementsByClassName?
    Please what am I doing wrong here?

  • @Uzosky
    getElementsByClassName(), as the name suggests, returns a list/multiple elements, doesn't it? (Not the same as e.g. getElementById(), which returns one.) So when you assign that to variable Elem, you cannot go Elem.innerHTML on a list/array. You will want more like:

    webviewer.runJavaScript("var elems = document.getElementsByClassName('highlight-span'); for (var i = 0; i < elems.length; i++) { elems[i].innerHTML = 'Hello!'"; })

  • @JonB Thank you for coming to the rescue again.

Log in to reply