transforming the use of getelementbyid into a plural form

Can a getElementById function work in plural context? Or would I need a different function or maybe jQuery?

<script type="text/javascript>
    window.onload = function() 
    {
        var test = document.getElementById('test');
        if (test) 
        {
            test.className = 'unactive';
            test.firstChild.onclick = function() 
            {
                if(this.parentNode.className == 'unactive') {
                    this.parentNode.className = 'active';
                } 
                else 
                {
                    this.parentNode.className = 'unactive';
                }
            }
        }
    };
</script>

Answer №1

Feel free to utilize this handy function:

document.selectByID = function(id){
    if(document.all)
        return document.all[id];
    var elements = [],
    all = document.getElementsByTagName('*');
    for(var i=0;i<all.length;i++)
        if(all[i].getAttribute('id')===id)
            elements.push(all);
    return elements;
}

By the way, as mentioned by @Pointy, the id attribute should be unique, whereas the class is used to categorize elements with common properties.

Answer №2

Assuming your intention is to perform actions on multiple elements based on a list of IDs. (If you are looking to select multiple elements with the same ID, this is not recommended as IDs should be unique. In such cases, consider using classes instead.)

To achieve this in jQuery: you can use a comma-separated list of id selectors (e.g., $("#foo, #bar, #baz")) and implement your function as follows:

$("#foo, #bar, #baz").addClass("unactive")
.children(":first-child").click(function() {
    var $this = $(this);
    var $parent = $this.parent();
    $parent.toggleClass("active unactive");
});

If you prefer not to use jQuery: here's a simple function that takes a list of IDs and returns an array of nodes:

function getElementByIdList() {
    var results = [];
    for(var i=0; i<arguments.length; ++i) {
        results.push(document.getElementById(arguments[i]));
    }
    return results;
}

You can use this function in your current code like so:

var myNodeArray = getElementByIdList("foo", "bar", "baz");
for(var i=0; i<myNodeArray.length; ++i) {
    var node = myNodeArray[i];
    if(node) {
        // Your code logic goes here...
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Label and Input Elements with Dynamic CSS through jQuery Values

Edit : I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Framework I cannot remove it. I'm trying to apply dynamic styling to the input and label elements in my HTML using jQuery. However ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

What methods could a web crawler use to access and analyze the content within ::before?

In the world of web development, a pseudo element like ::before or ::after may seem invisible in the DOM tree. It's a tricky situation because you can't just target it using a selector. So, how do you retrieve the content within a pseudo element ...

Using a hashtag in the URL to open an HTML <div> element

I have a website with two tabs labeled as Home and Action. When I hover over the Action tab, the URL changes to include #tab_action: https://i.sstatic.net/OOD5S.png Then, when I click on it, the related tab content opens: https://i.sstatic.net/JdcGG.pn ...

What are the best methods for obtaining live data for my web application?

In my current project, I have developed an HTML5 web application that displays various icons on Google Maps. The front-end is built with AngularJS and JavaScript, while the backend consists of a WebAPI, Entity Framework, and SQL database. At the moment, t ...

The trio of Javascript, Ajax, and FormData are

I'm struggling with sending form values to a PHP file. Here's the code I have: <form role="form" id="upload_form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="formlabel">Title< ...

"Implementing a feature to dynamically load Blogspot post content using JSON upon user

$.ajax({ url: 'https://uniquewebsite.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script', type: 'get', dataType: "jsonp", success: function(data) { var entry = data.feed.entry; ...

`A quirk in Jquery UI's range slider values``

I need some assistance with this code that is functioning correctly. $slider.slider({ min: 0 ,max: 500 ,range: true ,values: [0,500] ,step: 10 ,slide: function (event, ui){ $prev.text('₴' + ui.values[0]); ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

I am having trouble setting margins for a sticky position in a WordPress website

Can someone help me reposition the left-sidebar with a sticky top to be below the main header when scrolling down? Adding margin-top to sticky-top under col-sm-1 is not working. <style> .col-sm-1 .sticky-top { margin-top: 50px} </style> ...

Node.js encounter an error while processing an Ajax request

Running a node.js server on port 3000, my index.html file sends an Ajax request to a apache2 server on port 80 in order to retrieve the current cookie on the site. Despite seeing the cookie on the browser, no cookie response is received. The Ajax request i ...

Allocation failure encountered while using Express.js with MongoDB

Today, I encountered the same error message in the console twice, and the only solution was to restart the backend. My backend is built using Node/expressjs, and the frontend is developed with reactjs. The backend serves two websites - one for admin and on ...

Creating diagonal ribbon designs can add a unique and dynamic touch to any

Can anyone help me figure out how to create a ribbon similar to the image below using CSS? I have managed to make the slanted filled box with text inside, but I am having trouble with the flaps. Check out this CodePen link for reference. ...

Tips for changing the page URL upon click in a Vue.js application

I am currently developing a post board application using Vue.js and I am facing an issue with redirecting the page when a user clicks on each post. To handle this, I have made use of vue-route and axios in my project. Here is a snippet from index.js, ex ...

Issue: AngularJS modal not appearing when utilizing partial for template URLExplanation: The Angular

I am having trouble with a modal in a partial file that is supposed to be loaded into my main view using an ng-include tag. However, the template cannot be found and I do not see it being loaded in the console or network tab. The error message I receive is ...

jQuery is notorious for incorporating front-end JavaScript libraries that are riddled with security flaws

After conducting an optimization analysis of my website using Google Lighthouse, I came across a "Best Practices" issue that raised concerns: Some third-party scripts may pose security vulnerabilities that can be easily exploited by attackers. You can ac ...

Updating the content of a window without the need to refresh the page using JavaScript

Is there a way to navigate back to the previous window in chat_user without refreshing the entire page when the back button is clicked? Below is the code I have tried: <a href="" onclick="window.history.go(-1); return false;">back</a> ...

Straightforward, rudimentary example of Typescript knockout

I am hoping to successfully implement a basic TypeScript Knockout example. I utilized Nugget to acquire the TypeScript Knockout and downloaded Knockout 3.0.o js. Below is my TypeScript file: declare var ko; class AppViewModel { firstName = ko.observa ...

Is there a way to access a CSV file containing a comprehensive list of days and months?

I am in the process of designing a booking form for a website, and the client has specified that they prefer a drop-down menu for selecting dates rather than a traditional calendar. To achieve this, I plan to utilize gravity forms. For the date options, I ...

Retrieving data from a server using the GET method with parameters through axios in a React Native application

As someone new to Web requests, I have encountered a challenge that seems simple but has proven difficult for me. Despite searching the web, I am struggling to get a working response. When I input the URL 'http://www.test.com/callservice.php?action=s ...