What is the equivalent of using $('.class')
in JQuery
to get all elements by class name with pure JavaScript?
What is the equivalent of using $('.class')
in JQuery
to get all elements by class name with pure JavaScript?
document.getElementsByClassName(klass)
It is worth noting that some engines, especially older browsers, may not support this method. In such cases, using a shim could be considered. Although it may be slower and iterate over the entire document, it will still function.
UPDATE several years later: A similar result can now be achieved with
. While this may not seem significant, the latter allows for queries on any CSS selector, providing much greater flexibility. This is particularly useful if "get all elements by class name" is just one part of a larger goal, serving as the vanilla JS equivalent to jQuery's document.querySelectorAll('.klass')
$('.class')
.
An effortless method to achieve the desired result
let customers = document.getElementsByClassName('custid');
for (let i = 0; i < customers.length; ++i) {
let element = customers[i];
element.innerHTML = 'this is a new value';
}
var elements = document.querySelectorAll('.your class');
If that doesn't work, you can try creating your own custom classname like this:
if (!document.getElementsByClassName) {
document.getElementsByClassName=function(className) {
var allElements=document.getElementsByTagName('*'), matchingElements=[], i=0, element;
while(element=allElements[i++]) {
if (element.className == className) {
matchingElements.push(element);
}
}
return matchingElements;
}
}
While some browsers support the document.getElementsByClassName(class) function, others do not. If your browser does not have this feature, you will need to manually check each element in the document to see if it has the desired class name.
Many different methods were outlined and efficiency tested in this article: http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
function findElementsByClass(htmlElement, tagName, className){
var elements = (tagName == "*" && htmlElement.all)? htmlElement.all :
htmlElement.getElementsByTagName(tagName);
var returnElements = new Array();
className = className.replace(/\-/g, "\\-");
var regExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
var element;
for(var i=0; i<elements.length; i++){
element = elements[i];
if(regExp.test(element.className)){
returnElements.push(element);
}
}
return (returnElements)
}
Here is a simple solution:
function findElementsByClassName(className)
{
var foundElements = [];
var allTags = document.getElementsByTagName("*");
for(var i = 0; i < allTags.length; i++)
{
if(allTags[i].className == className)
{
foundElements.push(allTags[i]);
}
}
return foundElements;
}
When I receive a JSON response, I utilize nested JSON data from my GeoRegionCountries APIController and a custom class TreeView to structure the data for a plugin. The specific plugin I am using is a combo multi-select Treeview, accessible through this lin ...
I have a unique function for logging messages to the firebug console that I'd like to share: // Just having fun with names here function ninjaConsoleLog() { var slicer = Array.prototype.slice; var args = slicer.call(arguments); console.lo ...
As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...
My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...
My form has multiple checkboxes all with the same id "cbna". When I submit the form, I want the JavaScript code to check if at least one checkbox is checked. If no checkbox is checked, an alert should appear. If a checkbox is checked, the value stored in ...
I am currently working with the following HTML structure: <td class="prd-var-price"> <div class="price-total"> <span class="price-unit">€</span> <span class="price-value"> ...
I'm currently running an Arch Linux system with KDE plasma and I have a 50mb XML file that I need to parse. This XML file contains custom tags. Here is an example of the XML: <JMdict> <entry> <ent_seq>1000000</ent_seq&g ...
I recently developed a Drum Machine using ReactJS, but I'm facing an issue with making the buttons look like they've been clicked when I press the corresponding key. I came across a similar query on this site, however, I'm having trouble imp ...
I have developed a form on the client side which includes: <html> <body> <script> $(document).ready(function() { $.ajax({ url: "Search.html", type: "POST", dataType : "json", s ...
I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...
I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...
QUERY: I'm facing an issue with error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] when using Vetur with TypeScript installed in VSCode. How can I resolve this? CONTEXT: I integrated Vuelidate into a single-file ...
I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...
I had a function that was functioning correctly: $('#buttFurniture').click(onFilterCLick); However, when I decided to pass arguments to the function, it stopped working: $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture ...
I am currently in the process of transitioning my existing website to vuejs. The navigation structure I aim for is as follows: /login /signup /password-reset /browse /search ... numerous other paths Since some of these paths have similar functionalities, ...
I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...
Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...
submitTCtoDB() { console.log("The selected file list contains: " + this.selectedFileList) this.readFile().then(() => { alert("ReadFile has finished, now submitting TC"); this.submitTC() }); } readFile() { return new Promise((resolve, r ...
Is there a way to show only unique values from multiple divs with the same class name? <div class="categories">cat 1</div> <div class="categories">cat 1</div> <div class="categories">cat 2</div> <div class="categorie ...
I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...