I would like to hide an image on my site using this code:
$(document).ready(function(){ $('body').find('img[src$="myimage.png"]').remove(); });
Is there any way to convert this to javascript and still make it work in internet explorer??
i assume you mean convert to vanilla js (without needing jquery lib).. this should work
window.addEventListener("load", function(){
const els = document.getElementsByTagName("IMG");
for (let i = 0; i < els.length; i++){
let src = els[i].getAttribute("src");
if (src == "myimage.png") {
els[i].style.display = "none";
break;
}
}
});
Related
I have a reveal presentation in an iframe. Each slide has a div with an audio player in in and the divs id is "narration".
I have a button outside the frame that is used to hide/show this div. The problem is that it only does this for the first slide and not the rest.
EDIT : This seems to hide the divs :
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
HTML in iframe (There is one for each slide) :
<div id="narration"><p align="middle">
<audio controls="" preload="none">
<source src="mp3/2.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio></p>
</div>
JS (outside of iframe):
function checkAudio() {
if (document.getElementById('cb1').checked) {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'none';
} else {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'block';
}
}
After changing your IDs to classes (read here why), you need to update your javascript code to handle the multiple divs via a foreach loop.
function checkAudio() {
var narrationDivs = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var newDisplay = "block";
if (document.getElementById('cb1').checked) {
newDisplay = "none";
}
narrationDivs.forEach(function(div) {
div.style.display = newDisplay;
});
}
In order to have the code run again when your iframe changes, you need to update your iframe changing function:
function setURL(url){
document.getElementById('ppt').src = url;
checkAudio(); // Just run the function again!
}
If you want to show a specific element using a button, you should use a specific ID. If you want to show all items using a single button you should use classes. You could also use classes to show a specific element e.g.: The 5th button will show the 5th element but this is not a good style.
When the site in the iframe loads the next frame, your code doesn't know to hide the div it presents again. You need an event to process on.
You need to poll the id so that if it shows up again, you can hide it. See: iframe contents change event?
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
You might also want to check out the audio-slideshow plugin that allows to play separate audio files for each slide and fragment. If your main need is this, the plugin should do the job for you.
You can find a demo here and the plugin here. There is also the slideshow-recorder plugin that allows you to record your narration.
Asvin
I have another error caused by IE7 (great program...) I am trying to get a dropdownlist into a javascript function so that i can use it's values to hid some divs which are named after those values. but each time I try to use this dropdownlist I get the following error:
runtime-error microsoft jscript: dropdownlist is not defined
the javascript:
<script src="/Scripts/ShowHide.js" type="text/javascript"></script>
function ShowHideDivByDropDownList(dropdownlist) {
for (i = 0; i < dropdownlist.options.lenght; i++) {
var divId = dropdownlist.options[i].value;
if (divId != "") {
document.getElementById(divId).style.display = "none";
}
}
document.getElementById(drowdownlist.value).style.display = "block";
}
the dropdownlist:
#Html.DropDownList("MainList",
new SelectList(Model.ListCategories,
Model.List,
new { onchange ="ShowHideDivByDropDownList(this)"})
EDIT:
I have made allot of trail adjustments to try and make the script running, allot of people seem to have noticed this :). I have returned to script to it's original state, but the error still occurs.
If it's an ID use getElementById(id), if it's a name use getElementsByName(name)[0].
getElementByName doesn't exist.
Also be careful with your variable names...
In your for loop you have drowdownlish instead of drowdownlist. Just for sanity sake you may want to make those dropdownlist.
function ShowHideDivByDropDownList(dropdownlistid) {
var dropdownlist= document.getElementByName(dropdownlistid);
for (i = 0; i < dropdownlist.options.count; i++) {
var divId = dropdownlist.options[i].value;
if (divId != "") {
document.getElementById(divId).style.display = "none";
}
}
document.getElementById(dropdownlist.value).style.display = "block";
}
You can prevent yourself all this mess - as this answer correctly said, you have to use getElementById but if you change your code to this:
onchange ="ShowHideDivByDropDownList(this)"
Then you pass the actual object to the function then you can safely have such code instead:
function ShowHideDivByDropDownList(drowdownlist) {
for (var i = 0; i < drowdownlist.options.length; i++) {
var divId = drowdownlist.options[i].value;
if (divId !== "") {
var element = document.getElementById(divId);
if (element)
element.style.display = "none";
}
}
var element = document.getElementById(drowdownlist.value);
if (element)
element.style.display = "block";
}
Couple of things I fixed along the way as well:
In JavaScript, array length is .length, not .count
In case there's no element with such ID your code would crash - to avoid such mishap it's always good practice to validate you really have such element - you can add alert("element does not exist"); for debug purpose but having the whole code crash because you have typo is not a good thing.
I'm injecting JavaScript code into a website for personal use, using a Google Chrome extension... I'd like to hide all images before the page loads... I've got the script to run before anything loads, but can't seem to get the correct code to hide the array of images... something like:
function beforeload(){
document.getElementsByTagName('img')[0].style.display = "none"
}
Basically i want all the image tags to have style="display:none" added to the attributes. how do i do this?
You need to loop on them
var images = document.getElementsByTagName('img');
for (i = 0; i < images.length;i++ ) {
images[i].style.display = "none";
}
Amr has got the way to do it with javascript. If you add jquery to the page, it only takes one line
$('img').hide();
Below code will only hide images of all image elements
let images = document.getElementsByTagName("img");
let images_length = images.length;
for (let i = 0; i < images_length; i++) {
images[i].style.setProperty("display", "none", "important");
}
but what if images are displayed using CSS ?
Solution for all elements
let images = document.getElementsByTagName("img");
let images_length = images.length;
for (let i = 0; i < images_length; i++) {
images[i].style.setProperty("display", "none", "important");
}
/** now also hide images which are implemented in css */
let all_elements = document.querySelectorAll("*");
for(let i = 0 ; i < all_elements.length ; i++){
all_elements[i].style.setProperty("background-image","unset","important");
}
.image {
width : 100px;
height : 100px;
background-image : url(https://image.shutterstock.com/image-photo/aerial-view-main-faisal-mosque-600w-1242735640.jpg);
}
<img src="https://image.shutterstock.com/image-photo/aerial-view-main-faisal-mosque-600w-1242735640.jpg" width="100" height="100">
<div class="image"></div>
<div> To show images plz comment/remove js </div>
Check this out:
http://ncthakur.itgo.com/js09.htm
It's not exactly what are you looking for, but you can use some part of it.
It took me 7 seconds to find it on google ;)
In javascript I have a reference to a div. In that div is an anchor element with a name='foundItem'
How do I get a reference to the anchor with the name foundItem which is in the Div I have the reference of?
There are 'many' foundItem anchors in other divs on the page. I need 'this' DIVs one.
// assuming you're not using jquery or mootools
// assume div is mydiv
var lst = mydiv.getElementsByTagName('a');
var myanchor;
for(var i=0; i<lst.length; ++i) {
if(lst[i].name && lst[i].name == 'foundItem') {
myanchor = lst[i];
break;
}
}
// the mootools method
var myanchor = $(mydiv).getElement('a[name=foundItem]');
You can use the getElementsByTagName method to get the anchor elements in the div, then look for the one with the correct name attribute:
var found = null;
var e = divReference.getElementsByTagName('A');
for (var i=0; i < e.length; i++) {
if (e[i].name && e[i].name == 'foundItem') {
found = e[i];
break;
}
}
If found is not null, you got the element.
If you happen to use the jQuery library, you can let it do the searching:
var found = null;
var e = $(divReference).find('a[name=foundItem]');
if (e.length == 1) found = e.get(0);
Use a JavaScript library like jQuery and save yourself time.
var theAnchor = $('#divId a[name=foundItem]');
Using jquery, it's dead easy:
<script type="text/javascript">
$(function(){
var item = $("#yourDivId a[name=foundItem]")
)};
</script>
Update:
As per the comments, if you have control over what to id/name/class your anchor tag/s, it would be best to apply a class to them:
<div id="firstDiv">
test
</div>
<div id="secondDiv">
test another one
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){
var item = $("#firstDiv a.foundItem");
alert(item.html()); // Will result in "test"
var item2 = $("#secondDiv a.foundItem");
alert(item2.html()); // Will show "test another one"
)};
</script>
If you're doing anything with javascript, jQuery saves you tons of time and is worth investing the effort to learn well. Start with http://api.jquery.com/browser/ to get an intro to what's possible.
Not sure if this helps, but wanted a function to handle the load of a page dynamically and scroll to the anchor of choice.
function scrollToAnchor(anchor_val) {
alert("" + anchor_val);
var page = document.getElementById('tables');
var found = null;
var cnt = 0;
var e = document.getElementsByTagName('a');
for (var i = 0; i < e.length; i++) {
if (e[i].name && e[i].name == anchor_val) {
found = e[i];
break;
}
cnt++;
}
if (found) {
var nPos = found.offsetTop;
alert("" + nPos);
page.scrollBy(0, nPos);
} else {
alert('Failed with call of scrollToAnchor()' + cnt);
}
}
I'm trying to toggle the visibility of certain DIV elements on a website depending on the class of each DIV. I'm using a basic JavaScript snippet to toggle them. The problem is that the script only uses getElementById, as getElementByClass is not supported in JavaScript. And unfortunately I do have to use class and not id to name the DIVs because the DIV names are dynamically generated by my XSLT stylesheet using certain category names.
I know that certain browsers now support getElementByClass, but since Internet Explorer doesn't I don't want to go that route.
I've found scripts using functions to get elements by class (such as #8 on this page: http://www.dustindiaz.com/top-ten-javascript/), but I can't figure out how to integrate them with with my toggle script.
Here's the HTML code. The DIVs themselves are missing since they are generated on page load with XML/XSLT.
Main Question: How do I get the below Toggle script to get Element by Class instead of get Element by ID?
<html>
<head>
<!--This is the TOGGLE script-->
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
</head>
<!--the XML/XSLT page contents will be loaded here, with DIVs named by Class separating dozens of li's-->
Click here to toggle visibility of class 1 objects
Click here to toggle visibility of class 2 objects
</body>
</html>
The getElementsByClassName method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Usage:
function toggle_visibility(className) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}
Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.
Older Answer
You'll want to check into jQuery, which will allow the following:
$(".classname").hide(); // hides everything with class 'classname'
Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".classname").hide();
});
</script>
document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';
Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]
Use it to access class in Javascript.
<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>
adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:
function toggle_visibility(className,display) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];
if(display.length > 0) {
e.style.display = display;
} else {
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}
}
My solution:
First create "<style>" tags with an ID.
<style id="YourID">
.YourClass {background-color:red}
</style>
Then, I create a function in JavaScript like this:
document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'
Worked like a charm for me.
You can get the same result using document.querySelectorAll('.klass') as document.getElementsByClassName(klass).
It might not seem like much but querySelectorAll allows queries on any CSS selector which makes it much more flexible, in case "get all elements by class name" is just a step in what you are really trying to do. It is vanilla JS answer to jQuery's $('.class').
Source:
https://stackoverflow.com/a/9427330/3850405
For quick view in console, in below code viewing all elements text
for (let element of document.getElementsByClassName('classname')) {
console.log(element.text);
}