How to disable div blocks having a certain id pattern? - javascript

I would like to write a greasemonkey script to disable a div on a certain page.
On any given load of the page I don't know where in the DOM the div will be but I know it's always called <div id = "alertPanel"> ....</div>
How would I go about disabling this div?
My intial thoughts were something along the lines of:
var myDivs= document.getElementsByTagName('div');
for (i=0; i<myDivs.length; i++)
{
if (myDivs[i].<get id property somehow> = "alertPanel")
myDivs[i].style.visibility = 'hidden';
}
but as you can tell I'm stuck at accessing the id property for an equality check.
Incidently, I'm using a text editor to write this - I guessing that a standard javascript editor would give an autocompletion list after typing in myDivs[i].

If it has an id, you can use document.getElementById:
var div = document.getElementById("alertPanel");
Then if it exists, you can either remove it (probably a bad idea) or hide it:
if (div) {
div.style.display = "none"; // Hides it
// Or
// div.parentNode.removeChild(div); // Removes it entirely
}
Update: Re your comment on another answer:
thanks for your answer. Does your statemt apply to a page with iframes too. The div in question is in an iframe. I've tried ypur solution and it didn't work unfortunately. maybe a link to the page will help: tennis.betfair.com the div i want to disable is the one with id: minigamesContainer
If the element is in an iframe, then you have to call getElementById on the document that's in the iframe, since iframes are separate windows and have separate documents. If you know the id of the iframe, you can use document.getElementById to get the iframe instance, and then use contentDocument to access its document, and then use getElementById on that to get the "minigamesContainer" element:
var iframe, div;
iframe = document.getElementById("the_iframe_id");
if (iframe) {
try {
div = iframe.contentDocument.getElementById("minigamesContainer");
if (div) {
div.style.display = "none";
}
}
catch (e) {
}
}
(The try/catch is there because of a potential security error accessing the content of the iframe; I don't know Greasemonkey well enough to know whether the SOP applies to it. I tend to assume it doesn't, but better safe...)
If you don't know the id of the iframe or if it doesn't have one, you can just loop through all of them by getting them with document.getElementsByTagName and then looping:
var iframes, index, iframe, div;
iframes = document.getElementsByTagName("iframe");
for (index = 0; index < iframes.length; ++index) {
iframe = iframes[index];
try {
div = iframe.contentDocument.getElementById("minigamesContainer");
if (div) {
div.style.display = "none";
break;
}
}
catch (e) {
}
}
References:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Applications APIs

In valid HTML you can have only element with certain ID. So:
document.getElementById('alertPanel').style.visiblity = 'hidden';
But if you still need to iterate all div's and check their ID's, then this should work:
if (myDivs[i].id == "alertPanel") myDivs[i].style.visibility = 'hidden';

Related

Trying to add css styling to iframe with JavaScript

Trying this on Wordpress:
Inside my iframe I have a ._2p3a class I want to change its width to ._2p3a {width: 100% !important;}.
With CSS its not possible to access that class so I am trying with JavaScript:
MY JS CODE:
function hello() {
let myiFrame = document.getElementById("iframe-css");
let doc = myiFrame.contentDocument;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
}
//the iframe id > "iframe-css"
code Source: https://redstapler.co/how-to-apply-css-to-iframe/
The error:
land_page.js?ver=1.0:4 Uncaught TypeError: Cannot read property 'body' of null
at hello (land_page.js?ver=1.0:4)
at HTMLIFrameElement.onload ((index):539)
underlined code:
.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
Tried: Using CSS to affect div style inside iframe
(got errors with all examples "None worked").
I am running this function with onload="hello(this)" on my iframe.
Any other suggestions how I can edit that class to make its width 100%??
please try bellow code ... I hope you get result:
let myiFrame = document.getElementById("iframe-css").contentWindow;
let doc = myiFrame.document;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
Adding a <style> element isn't the best way to do this. However, even if it was, you should try to avoid adding elements via innerHTML. It is better to use Document.createElement (document is an instance of Document) and Element.appendChild (all elements are instances of the Element class).
The best way to do this is by directly modifying the style of the elements in the class.
function hello() {
let myiFrame = document.getElementById("iframe-css");
let doc = myiFrame.contentDocument ?? myiFrame.contentWindow?.document ?? new Document();
let elements = doc.getElementsByClassName("2p3a");
for(let i = 0; i < elements.length; ++i) {
elements[i].style.width = "100%";
}
}
Also, the onload attribute sometimes doesn't work on an iFrame. You may have to use the DOM like this:
document.getElementById("iframe-css").onload = hello;
On a side note, you should generally stick to 2 or 4 spaces of indentation in JavaScript, but you chose 3.
Decided to use a different plugin since using the facebook iframe was causing some trouble. With this new plugin everything is working fine so yea.
Thanks to anyone who put effort to answering, I appreciate your help.

get a dynamic id from an iframe in an iframe

I am actually doing a tricky task, I have to create pack of resource(which are pages on the website), to do so I use iframe to display the content of the pages. But I can have multiples Iframes in one Iframe.
And I want to pass some style on those iframe in iframe, so i have to target them.
I have a special node id for each pages that allow me to return only the body.
So my question is how do I get to target the id of my iframe in my iframe which I tried to do with that line var get_iframe_inside = search_inside.getElementsByTagName("iframe".id); to then modify it's style.
I know that I am not using the right way for this line, but I have been scratching my head all this morning and can't find a way.
function test(id){
var iframe = window.parent.document.getElementById(id); //select my first iframe
get_iframe_inside(id); //call my function to get the iframe in the iframe
function get_iframe_inside (id){
var search_inside = (iframe.contentDocument) ?iframe.contentDocument : iframe.contentWindow.document;
//My goal is then to modify some properties
var get_iframe_inside = search_inside.getElementsByTagName("iframe".id);
$(get_iframe_inside).css({'padding':'0px 50px', 'background-color':'#cecece'});
}
}
Well it was kind of trivial my code was nearly working i just didn't tought at how to get thoses ids.
i just had to get them by tag and after that to do an iteration with for.
var get_iframe_inside = search_inside.getElementsByTagName("iframe");
var i;
for (i = 0; i < get_iframe_inside.length; i++){
get_iframe_inside[i].style.padding='0px 50px';

How to write JavaScript for iframe and not iframe (same content)

Setup
I will be accessing content on my page sometimes from an iframe and sometimes from the same content not in an iframe.
Problem
I'm trying to figure out a way to write javascript once and include both ways of accessing that content during the declaration of the var...
so far example
var $Holder;
if($('#MyHolder iframe').contents().length > 0) {
$Holder = $('#MyHolder iframe');
}
else {
$Holder = $('#MyHolder');
}
but I can't do this since if the content is in an iframe I need to access it this way:
$Holder.contents().find('#SomeButton').on('click',function(){});
and this doesn't work if the content is directly on the page. This also does not work if I add .contents().
If I understand the question correctly, you should be able to set your $Holder to the contents() of the iframe like so:
var $Holder;
if($('#MyHolder iframe').contents().length > 0) {
$Holder = $('#MyHolder iframe').contents();
}
else {
$Holder = $('#MyHolder');
}
Then you should be able to access elements in either case like so:
$Holder.find('#SomeButton').on('click',function(){});

Remove iframe with javascript

I am trying to remove iFrame tags in my documents.
This is the function. But it don't seem to work. Here is my sample code
<script>
function removeiframe() {
alert("Hello Lovely World");
var markup = document.body.innerHTML;
var filtered=markup.replace(/(<iframe.*?>.*?<\/iframe>)/g,"");
alert("he: " + markup);
//markup = Regex.Replace(markup, #"<script.*?/script>", "", RegexOptions.IgnoreCase);
//markup = Regex.Replace(markup, #"<iframe.*?/iframe>", "", RegexOptions.IgnoreCase);
markup = filtered;
document.body.innerHTML = markup + "<hr><hr>HELLO";
}
</script>
<body onload="removeiframe()">
<iframe marginheight="0" src="http://www.hotelanswer.com" marginwidth="0" frameborder="0" height="180" scrolling="no" width="210"></iframe><br>
</body>
Here's a script you can run that will remove all the iframes from your document. Here's an example of this working: http://jsfiddle.net/5hh9H/
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].parentNode.removeChild(iframes[i]);
}
Pure Javascript code:
document.querySelectorAll('iframe').forEach(
function(elem){
elem.parentNode.removeChild(elem);
});
You didn't mention why you need to remove iframes in the document.
I do it in order to prevent Clickjacking attack. But it will work in any cases.
You need this:
<style id="defendClickjack" type="text/css">body{display:none;}</style>
and then
<script type="text/javascript">
if (self === top) {
var defendClickjack = document.getElementById("defendClickjack");
antiClickjack.parentNode.removeChild(defendClickjack);
}
else {
top.location = self.location;
}
</script>
You can find more information here:
https://www.owasp.org/index.php/Clickjacking
http://en.wikipedia.org/wiki/Clickjacking
Slight improvement here to Matt's original example if you want to only do it on mobile. For me, the use case was that I'm using a Vimeo embed on my site to create a video background. I needed to ditch the video on mobile for performance. This does the job.
$( document ).ready(function() {
let isMobile = window.matchMedia("only screen and (max-width:650px)").matches;
if (isMobile) {
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].parentNode.removeChild(iframes[i]);
}
}
});
s.ermakovich's comment about code not working properly with more than one iframe is not 'wrong' but a bit misleading...and depends on the situation. My Vimeo iFrame had a child frame making requests that continued after DOM complete. Matt's code did destroy both.
In my case my 2nd iframe was a direct child of the parent. The code might not work if you have several iframes on a page that are not direct children of the same parent and you just copy and paste that code. In this case you need to be more specific:
If you have multiple iFrames on your page you can add specificity to your query selector. Your choice if you want to use querySelectorAll() or not based on the situation, but I see no reason why querySelector() can't be used either.
document.querySelector(".foo > bar iframe")
document.querySelector("foo bar > iframe")
If you have a grid of iframes, perhaps several embedded videos in a row perhaps
document.querySelectorAll("foo > .bar > iframe")
or maybe better from the same data source...
document.querySelectorAll("iframe[data-src]")
Someone please correct me if I'm wrong somewhere
You should put the iframe inside of a div element.
<div id="kk">
//your iframe
</div>
Then use jQuery to remove the iframe.
$('#kk').click(function(){
$(this).html("");
});
This is a possible solution.

Get specific content in iframe without jquery

i want to get spesific contents (all of spans in .y6) in iframe without jQuery,
How can i write it only javascript?
"#canvas_frame" is an iframe
spans = $("#canvas_frame").contents().find(".y6>span");
If the iframe is on the same domain as the parent page you can use the iframe's contentWindow property.
Something like the below should help you out:
var canvasFrame = document.getElementById('canvas_frame').contentWindow,
allSpans = canvasFrame.document.getElementsByTagName('span'),
spans = [],
i;
i = allSpans.length;
while(i--){
if(/y6/.test(allSpans[i].parentNode.className)){
spans.push(allSpans[i]);
}
}

Categories