javascript: getElementsByClass - javascript

Im looking to do something simple and the site is not heavy with js so im not using a js framework for this.
I am trying to add event click listener, I am trying to get element by class. I found the following function + others that I have tried but for some reason none of them are finding the elements.
function getElementsByClass( searchClass, domNode, tagName) {
if (domNode == null) domNode = document;
if (tagName == null) tagName = '*';
var el = new Array();
var tags = domNode.getElementsByTagName(tagName);
var tcl = " "+searchClass+" ";
for(i=0,j=0; i<tags.length; i++) {
var test = " " + tags[i].className + " ";
if (test.indexOf(tcl) != -1)
el[j++] = tags[i];
}
return el;
}
var els = getElementsByClass("wow");
alert(els.length);
i have a couple of divs with the class wow, testing but I keep getting 0.

Assuming your function works properly, do it when the DOM is ready or on window load. Or call it before the end body tag.
DEMO: http://jsfiddle.net/rXApk/

The class attribute takes a space separated list of class names, not a comma separated list.
Your test won't match wow, as it looks for wow.

Related

Show/Hide image before filtering a table isn't working

I have web page with some really large tables that I'm filtering using some jquery routines I wrote. Anyway, when these tables get really large and the filtering functions can take some time to complete. So I figured I'd unhide a animated gif so the user had some feedback. However, the gif never appears when I call:
$('#loadingimg').show();
Unless I put an alert statement in front of it. I apologize for the ugly code, I'm not an experienced jquery/javascript programmer.
function filter()
{
var eles = ["mtmprogram","rate","stage"];
var tag;
var classes='';
$('#loadingimg').show();
//alert('hi');
$('.report').hide();
for (var i in eles)
{
tag = '#' + eles[i] + ' option:selected';
if ($(tag).val())
{
//$('.'+ $(tag).val()).show();
classes = classes + '.' + $(tag).val();
}
}
if (classes == '')
$('tr.report').show();
else
$(classes).show();
filterSubtables('Loan Number');
$('#loadingimg').hide();
}
Many thanks!
Maybe you aren't giving the #loadingimg element enough time to display. You could test this by running the rest of your code in a timeout:
function filter()
{
var eles = ["mtmprogram","rate","stage"],
classes = '';
$('#loadingimg').show();
//alert('hi');
setTimeout(function () {
$('.report').hide();
for (var i = 0, len = eles.length; i < len; i++)
{
var $tag = $('#' + eles[i] + ' option:selected');
if ($tag.val())
{
//$('.'+ $tag.val()).show();
classes = classes + '.' + $tag.val();
}
}
if (classes == '')
$('.report').show();
else
$(classes).show();
filterSubtables('Loan Number');
$('#loadingimg').hide();
}, 500);
}
Notice that I changed how the tag variable is used (this creates less CPU overhead to make less jQuery selections and to use as local a variable as possible). I also changed your loop to a better format that performs amazingly faster than for ( a in b ): http://jsperf.com/jquery-each-vs-for-loops/2

Removing a class from an HTML element using JavaScript

I am attempting to remove a class from an html tag using JavaScript but I have no idea where to start. I have searched but to no avail. While I am decently fluent in jQuery, I am not in JavaScript and I need to use JavaScript in this instance Anything I have found thus far would need to be adjusted for my own use, which I have not been successful at. Hopefully someone can explain it in a fool-proof way.
The element the class is attached to is the "ul" tag. The class is named "nojavaScript" and is only applied to this single instance of the "ul" tag. While as I said the class is only used once in the page, the "ul" tag is used in other instances with different classes or ids.
If it would make it easier for the JavaScript, I can change the class to an id.
I hope I have given you enough to go on. I will include an example of the html code below.
<ul id="lines_list" class="nojavaScript"></ul>
As I mentioned, if it's easier to remove an id than a class, I can make the current id a class, and the current class an id. But essentially it's the "nojavaScript" that needs to be removed.
Thanks!
Here's a pure js solution:
var ulArr = document.getElementsByClassName('nojavaScript');
for (var i = 0; i < ulArr.length; i++) {
ulArr[i].className = ulArr[i].className.replace('nojavaScript','');
}
First you select all elements with the given class name, then iterate over the result and replace the given class in the className attribute with an empty string.
UPDATE:
Here's a more robust solution that turns the removal into a parameterized function and handles stripping extra whitespaces from the beginning, end, and middle of the className attribute.
function removeClass(elem, className) {
//declare some regexes to help us strip the extra whitespace
var trimLeft = /^\s+/,
trimRight = /\s+$/,
stripDouble = /\s+/g;
//remove the class, strip extra whitespace, and reassign className
elem.className = elem.className.replace(className, '').replace(trimLeft, '').replace(trimRight, '').replace(stripDouble, ' ');
}
//declare name of class to remove and get an array of elements with that class
var toRemove = 'nojavaScript',
elArr = document.getElementsByClassName(toRemove);
//iterate over elements and remove the class
for (var i = 0; i < elArr.length; i++) {
removeClass(elArr[i], toRemove);
}
Here's a live demo ->
try this:
document.getElementById("lines_list").className = "";
function removeCSSClass(element, className) {
var cssClass = ' ' + element.className + ' ';
var index = cssClass.indexOf(' ' + className + ' ');
if (index >= 0) {
var newClass = cssClass.substr(0, index) + ' ' + cssClass.substr(index + className.length + 1);
element.className = newClass;
}
}
UPDATE: code now works in all occassions
function removeClassFromElement(el,className){
var classes = el.getAttribute('class').split(/[ ]+/g);
var class = "";
for(var i in classes)
if(classes[i] != className)
class += classes[i] + " ";
el.setAttribute('class',class);
}
removeClassFromElement(document.getElementById('lines_list'),'nojavaScript');
Here's a non regex method that is considerate of multiple classes on an element.
function removeClass(element, cssClass) {
var classes = element.className.split(' ');
var j = classes.length;
while (j--) {
if (classes[j] === cssClass) {
classes.splice(j, 1);
}
}
element.className = classes.join(' ');
}
var lines_list = document.getElementById('lines_list');
removeClass(lines_list, 'nojavaScript');
It splits on spaces to isolate whole class names whereas doing a simple search for the class name string and replacing with nothing might eat part of a longer class name.
Class name modification should be done on the className property with a RegExp replace to avoid clobbering other classNames which should stay:
var ele = document.getElementById( 'lines_list' );
ele.className = ele.className.replace( /(?:^|\s)nojavaScript(?:\s|$)/gm, ' ' );
http://jsfiddle.net/JAAulde/nWzaZ/3/
(genercized class names: http://jsfiddle.net/JAAulde/nWzaZ/2/ )
Without this regex, you either wipe the entire className, or you overkill and possibly take out a portion of foonojavaScript as well (you know, if you had such an odd class :P ). While this might not really be likely, it's good practice for when you run into code that might not be as specific.
This solution allows you to have as many classes on the element as you want, as similar as you desire, without worry of how you format them other than as specified by the W3C. No maintenance issues :).
(The RegExp specifically looks for your class preceded by start of string or white-space, and followed by white-space or end of string)
(This assumes you already have a handle on how to get the element(s) from the DOM in the first place.)

Chrome browser extension that detects hashtags in page

As personal project I would like to build a Chrome extension that will find all hashtags on a page. I don't much about JS or jquery so I wonder how I should approach this?
EDIT:
The Chrome Extension injects javascript after the page has loaded, but I need to scan the whole document for a hashtag. It is looking through the whole document that I am not sure how to do.
Thanks!
If you mean simply anchor tags with a href that has a # in it then:
var aTags = document.getElementsByTagName("a");
for(var index = 0; index < aTags.length; index++){
if(aTags[index].href.indexOf("#") != -1){
alert("found one");
}
}
Or if you want something more general, one way to return the entire webpage is simply:
document.body.innerHTML //A string containing all the code/text inside the body of the webpage.
And then you can do some indexOf or a regex search/replace depending on what you want to do specifically.
But if you know that the hashtag you are looking for is always in some container like a anchor or even just a div with particular class then I would go with that instead of working with the entire page. Here is a list of useful methods to parse up a webpage:
document.getElementsByTagName("a"); //already mentioned
document.getElementsById("id");
document.getElementsByName("name");
//and a custom function to get elements by class name(I did not write this)
function getElementsByClass(searchClass, domNode, tagName)
{
if (domNode == null) domNode = document;
if (tagName == null) tagName = '*';
var el = new Array();
var tags = domNode.getElementsByTagName(tagName);
var tcl = " "+searchClass+" ";
for(i=0,j=0; i<tags.length; i++)
{
var test = " " + tags[i].className + " ";
if (test.indexOf(tcl) != -1)
{
el[j++] = tags[i];
}
}
return el;
}

How to Get Element By Class in JavaScript?

I want to replace the contents within a html element so I'm using the following function for that:
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
ReplaceContentInContainer('box','This is the replacement text');
<div id='box'></div>
The above works great but the problem is I have more than one html element on a page that I want to replace the contents of. So I can't use ids but classes instead. I have been told that javascript does not support any type of inbuilt get element by class function. So how can the above code be revised to make it work with classes instead of ids?
P.S. I don't want to use jQuery for this.
This code should work in all browsers.
function replaceContentInContainer(matchClass, content) {
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
elems[i].innerHTML = content;
}
}
}
The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.
jsFiddle Example, using Vanilla JS (i.e. no framework)
Of course, all modern browsers now support the following simpler way:
var elements = document.getElementsByClassName('someClass');
but be warned it doesn't work with IE8 or before. See http://caniuse.com/getelementsbyclassname
Also, not all browsers will return a pure NodeList like they're supposed to.
You're probably still better off using your favorite cross-browser library.
document.querySelectorAll(".your_class_name_here");
That will work in "modern" browsers that implement that method (IE8+).
function ReplaceContentInContainer(selector, content) {
var nodeList = document.querySelectorAll(selector);
for (var i = 0, length = nodeList.length; i < length; i++) {
nodeList[i].innerHTML = content;
}
}
ReplaceContentInContainer(".theclass", "HELLO WORLD");
If you want to provide support for older browsers, you could load a stand-alone selector engine like Sizzle (4KB mini+gzip) or Peppy (10K mini) and fall back to it if the native querySelector method is not found.
Is it overkill to load a selector engine just so you can get elements with a certain class? Probably. However, the scripts aren't all that big and you will may find the selector engine useful in many other places in your script.
A Simple and an easy way
var cusid_ele = document.getElementsByClassName('custid');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
item.innerHTML = 'this is value';
}
I'm surprised there are no answers using Regular Expressions. This is pretty much Andrew's answer, using RegExp.test instead of String.indexOf, since it seems to perform better for multiple operations, according to jsPerf tests.
It also seems to be supported on IE6.
function replaceContentInContainer(matchClass, content) {
var re = new RegExp("(?:^|\\s)" + matchClass + "(?!\\S)"),
elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if (re.test(elems[i].className)) {
elems[i].innerHTML = content;
}
}
}
replaceContentInContainer("box", "This is the replacement text.");
If you look for the same class(es) frequently, you can further improve it by storing the (precompiled) regular expressions elsewhere, and passing them directly to the function, instead of a string.
function replaceContentInContainer(reClass, content) {
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if (reClass.test(elems[i].className)) {
elems[i].innerHTML = content;
}
}
}
var reBox = /(?:^|\s)box(?!\S)/;
replaceContentInContainer(reBox, "This is the replacement text.");
This should work in pretty much any browser...
function getByClass (className, parent) {
parent || (parent=document);
var descendants=parent.getElementsByTagName('*'), i=-1, e, result=[];
while (e=descendants[++i]) {
((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
}
return result;
}
You should be able to use it like this:
function replaceInClass (className, content) {
var nodes = getByClass(className), i=-1, node;
while (node=nodes[++i]) node.innerHTML = content;
}
var elems = document.querySelectorAll('.one');
for (var i = 0; i < elems.length; i++) {
elems[i].innerHTML = 'content';
};
I assume this was not a valid option when this was originally asked, but you can now use document.getElementsByClassName('');. For example:
var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);
See the MDN documentation for more.
There are 3 different ways to get elements by class in javascript. But here for your query as you have multiple elements with the same class names you can use 2 methods:
getElementsByClassName Method - It returns all the elements with the specified class present in the document or within the parent element which called it.
function ReplaceContentInContainer(className, content) {
var containers = document.getElementsByClassName(className);
for (let i = 0; i < containers.length; i++) {
containers[i].innerHTML = content;
}
}
ReplaceContentInContainer('box', 'This is the replacement text');
<div class='box'></div>
querySelectorAll Method - It select element on the basic of CSS selectors. Pass your CSS class to it with a dot and it will return all the element having specified class as an array-like object.
function ReplaceContentInContainer(className, content) {
var containers = document.querySelectorAll(`.${className}`);
for (let i = 0; i < containers.length; i++) {
containers[i].innerHTML = content;
}
}
ReplaceContentInContainer('box', 'This is the replacement text');
<div class='box'></div>
I think something like:
function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
elems[i].innerHTML = content;
}
}
}
would work
jQuery handles this easy.
let element = $(.myclass);
element.html("Some string");
It changes all the .myclass elements to that text.
When some elements lack ID, I use jQuery like this:
$(document).ready(function()
{
$('.myclass').attr('id', 'myid');
});
This might be a strange solution, but maybe someone find it useful.

Process HTML in javascript

I would like to remove all instances of a .class in an html.
remove class "s"
remove <span class="s">some text</span> in html
Output
remove some text in html
What's the easiest way to do this?
Assuming you want to remove it from just this class. Here's how to keep just the text:
$(".s").each(function(){
$(this).replaceWith($(this).text());
});
Code in action.
And if you want to keep the HTML:
$(".s").each(function(){
$(this).replaceWith($(this).html());
});
And here's that code in action.
Here's a plain JavaScript solution. It might look a bit long at first sight, but it simply does what you want:
function moveElements(root) {
var parent = root.parentNode,
e = root.firstChild;
while (e != null) {
var next = e.nextSibling;
parent.insertBefore(e, root);
e = next;
}
parent.removeChild(root);
}
function removeClass(root, name) {
var e = root.firstChild;
while (e != null) {
var next = e.nextSibling;
if (e.nodeType == 1) { // element node
if (e.className == name)
moveElements(e); // move children outside this element
else
removeClass(e, name); // else recursively scan this element
}
e = next;
}
}
removeClass recursively scans elements looking for the specified class, and if found, calls moveElements, which moves the children outside and removes the original element. To run it through the entire document, removing the class s (from your example), call it like this:
removeClass(document.documentElement, 's');
Here's a working example on JSBin.
replaceNode?
http://www.webreference.com/js/column43/replace.html
The replaceNode method is much more intuitive than the removeNode method. While the removeNode method just removes the specified element and makes its descendents children of their grandfather, the replaceNode method deletes the whole subtree that is rooted at the specified element, and substitutes it with a new element.
var msg = "";
function printChildren() {
childCount = bodyNode.childNodes.length;
msg += "childCount = " + childCount;
for(var i = 0; i < childCount; i++) {
msg += "\nchildNodes["+i+"].nodeName = " + bodyNode.childNodes[i].nodeName;
}
}
printChildren();
msg += "\nReplacing Paragraph 3\n";
var b = document.createTextNode("New Body Page");
var replacedNode = p3Node.replaceNode(b);
msg += "\nreplacedNode.nodeName = " + replacedNode.nodeName;
msg += "\nreplacedNode.childNodes.length = " + replacedNode.childNodes.length;
msg += "\np2Node.nodeName = " + p2Node.nodeName;
printChildren();
alert(msg);
Using jQuery you could do:
$(".s").remove();
http://api.jquery.com/remove/

Categories

Resources