How to getElementByClass instead of GetElementById with JavaScript? - javascript

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);
}

Related

How to hide element in internet explorer without jquery?

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;
}
}
});

Javascript doesn't work in IE, works fine in everything else

I am new to JavaScript and tried putting together an FAQs section that limits the number of shown answers to just 1 at a time. The JavaScript is here (also live at http://indulge.cc/indulge.js). For the whole live site, check out http://www.indulge.cc. You will see in FF, Chrome, Safari, etc. that the FAQs bit works, but doesn't go in IE. Don't know what I missed. Syntax?
function showonlyone(shownanswer)
{
var faqswitcher = document.getElementsByTagName('div');
for (var x=0; x<faqswitcher.length; x++)
{
name = faqswitcher[x].getAttribute('class');
if (name == 'faqswitcher')
{
if (faqswitcher[x].id == shownanswer)
{
if (faqswitcher[x].style.display == 'block')
{
faqswitcher[x].style.display = 'none';
}
else
{
faqswitcher[x].style.display = 'block';
}
}
else
{
faqswitcher[x].style.display = 'none';
}
}
}
}
Get the class attribute by querying the className property, instead of going after the attribute.
name = faqswitcher[x].className;
It works as well in the other browsers, and older IE's require it.

enable disable stylesheet using javascript in chrome

Rephrase of question: What is the best way to provide alternate stylesheets for a document?
I have a list of stylesheets, all of which are referenced in the html file.
I use javascript to disable all but one file.
example:
style1 disabled = false
style2 disabled = true
In practice, the last stylesheet to load (style2) is the active one, regardless of the disabled property.
How can I alternate between stylesheets on a document in chrome?
I tried to set the value of href attribute, but it seems to be read only.
example of code I have been using: (I am using an object called MenuStyles that is storing various css information)
function setActiveStyleSheet(name) {
var selectedSheet;
var currentSheet;
for (var i = 0; i < MenuStyles.styleSheets.length; i++) {
currentSheet = MenuStyles.styleSheets[i];
if (currentSheet.name === name) {
selectedSheet = currentSheet.sheetObj;
currentSheet.disabled = false;
} else {
currentSheet.disabled = true;
}
}
return selectedSheet;
}
EDIT: it turns out the problem was due entirely to bugs in the code. disabled property works fine. below is the fixed function:
function setActiveStyleSheet(name) {
var selectedSheet;
var currentSheet;
for (var i = 0; i < MenuStyles.styleSheets.length; i++) {
currentSheet = MenuStyles.styleSheets[i];
if (currentSheet.name === name) {
selectedSheet = currentSheet.sheetObj;
currentSheet.sheetObj.disabled = false;
} else {
currentSheet.sheetObj.disabled = true;
}
}
return selectedSheet;
}
In general you'd subclass off the BODY tag and use a single stylesheet that uses these classes. Then just swap the BODY class, not the sylesheet. Otherwise, you should be doing this server-side.
<body class="sheet1">
then
sheet1.h1 {
...
}
sheet2.h1 {
...
}
If you know the order of your stylesheets you can use-
document.styleSheets[i].disabled=true or
document.styleSheets[i].disabled=false;
If you have 2 stylesheets you can toggle between them with-
var S=document.styleSheets;
if(S[0].disabled){
S[0].disabled=false;
S[1].disabled=true;
}
else{
S[1].disabled=false;
S[0].disabled=true;
}
Current browsers offer reasonable ability to dynamically enable/disable stylesheets through the use of either the 'disabled' DOM property (Gecko) or by adding/removing the disabled attribute (Webkit and IE).
Unfortunately, these approaches only reliably work on 'link' tags that reference an external stylesheet (not 'style' tags), unless you are using IE10+. Yes - I said that - only IE does the right thing here.
For inline CSS using 'style' tags on non-IE browsers, you need to find a more crude way to enable/disable like those discussed above (remove the style element, etc).
I was able to get this to work with setting the disabled property and by including a 'title' attribute the stylesheets.
title property makes the stylesheet PREFERRED rather than PERSISTENT. see http://www.alistapart.com/articles/alternate/
I've found a great way (IMHO) to achieve this:
Let's suppose you know the exactly order of your stylesheet. Let's say you want to alternate stylesheet 0 and 1 (first and second):
To get a stylesheet state (enabled/disabled) you can try this (i.e. testing the second one):
document.styleSheets[1].disabled
...and it returns trueor false.
So to alternate you can write this code in an onclick event:
document.styleSheets[0].disabled = !(
document.styleSheets[1].disabled = !(document.styleSheets[1].disabled)
);
HTH!
For me if the link is disabled, document.styleSheets does not return the link in the collection ( in Chrome) . Only the enabled links are returned.
I use document.head.getElementsByTagName('LINK'), to get them all, out of HEAD.
Like:
private changeStyle(styleName: string): void {
const links = document.head.getElementsByTagName('LINK');
for (let i = 0; i < links.length; i++) {
const link = links[i] as any;
if( !link.href) continue;
if (link.href.indexOf(styleName) === -1) {
link.disabled = true;
} else {
link.disabled = false;
}
}
}

IE7 javascript error: runtime-error microsoft jscript: dropdownlist is not defined

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.

Javascript - How to remove link within links

Let's say a string contains http://google.com. When I linkify the whole string (that has both unlinked URLs and linked URLs, like the one shown above), it will become http://google.com">http://google.com</a>.
Is there a way to revert the incorrect links (which are the ones already linked before linkifying) back to http://google.com?
I found in WordPress, that it uses $ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret); (in wp-includes/formatting.php) to accomplish this. Can someone help me to do this in JavaScript?
Have a look at this http://jsfiddle.net/mplungjan/V5Qca/
<script>
function linkify(id,URL) {
var container = document.getElementById(id);
var links = container.getElementsByTagName("a");
if (links.length ==0) {
container.innerHTML=container.innerHTML.link(URL);
return;
}
var nodes = container.childNodes;
for (var i=nodes.length-1;i>=0;--i) {
if (nodes[i].nodeType ==3 && nodes[i].parentNode.nodeName!="A") {
var link = document.createElement("a");
link.href=URL;
link.innerHTML=nodes[i].nodeValue;
container.replaceChild(link, nodes[i]);
}
}
}
window.onload=function() {
linkify("div1","http://www.google.com/");
}
</script>
<div id="div1">
this is a test of replacing text with links with linkified content
</div>

Categories

Resources