How to use getElementsByClassName with WebEngine runJavascript
-
wrote on 30 Sept 2019, 08:13 last edited by
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: "https://developer.mozilla.org/en-US/" 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? -
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: "https://developer.mozilla.org/en-US/" 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?wrote on 30 Sept 2019, 13:45 last edited by JonB@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 variableElem
, you cannot goElem.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!'"; })
-
@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 variableElem
, you cannot goElem.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!'"; })
1/3