I am trying to modify the TrustPilot widget on my site.
The basic structure of the TrustPilot widget is:
#tp-widget_wrapper .tp-widget-wrapper
#wrapper-top .wrapper-top
#tp-widget-reviews-wrapper .tp-widget-reviews-wrapper hidden-element
#tp-widget-reviews .tp-widget-reviews
.tp-widget-review
.tp-widget-stars
.date
I am trying to hide the div .date
.
What I have gotten so far is:
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0];
var date_tags = trustpilot_frame.document.getElementsByClassName("date");
date_tags.style.display = "none";
However I get the error:
Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined
The var trustpilot_frame is finding the iframe, I just can't access anything within it.
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0].contentDocument;
console.log(trustpilot_frame);
var date_tags = trustpilot_frame.getElementsByClassName("date");
console.log(date_tags);
date_tags.style.display = "none";
Console:
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0].contentDocument;
var style_tag = trustpilot_frame.createElement("style");
style_tag.textContent = ".date{display:none;}";
trustpilot_frame.getElementsByTagName("head")[0].appendChild(style_tag);
console.log(trustpilot_frame);
Console:
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0].contentDocument;
trustpilot_frame.onload = setTimeout(hide_dates, 10000);
function hide_dates(){
// method 1
var style_tag = trustpilot_frame.createElement("style");
style_tag.textContent = ".date{display:none;}";
trustpilot_frame.getElementsByTagName("head")[0].appendChild(style_tag);
console.log(trustpilot_frame);
// method 2
var date_tags = trustpilot_frame.getElementsByClassName("date");
console.log(date_tags);
date_tags.style.display = "none";
}
Console shows the same as EDIT2 for the dom and the first EDIT for date_tags
To get the document of an iframe you need to use document.getElementById('iframe').contentDocument
you should then be able to use getElementsByClassName
https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentDocument
Your updated code would look like:
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0];
var date_tags = trustpilot_frame.contentDocument.getElementsByClassName("date");
date_tags.style.display = "none";
Try the below to wait for the iframe to load.
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0];
trustpilot_frame.onload = function() {
var date_tags = trustpilot_frame.contentDocument.getElementsByClassName("date");
date_tags.style.display = "none";
}