JS changes the ID in HTML

I have a code snippet that displays "hello world" where each word has its own unique style applied using CSS.

I am trying to implement a functionality where clicking on either "hello" or "world" will swap their respective styles. However, my current implementation is not working as intended. Can anyone help me identify the issue?

<html>
<head>
<style>
#today{
    font-weight: bold;
    color: red;
}

#normal{
    font-weight: normal;
    color: green;
}
</style>
<script>
    old="old";

        function set(in){
            var e = document.getElementsByName(old);
            for(ii=0;ii<e.length; ii++)
            {
                var obj = document.getElementsByName(old).item(ii);
                obj.id="normal";
            }
            old=in;
    var e = document.getElementsByName(old);
            for(ii=0;ii<e.length; ii++)
            {
                var obj = document.getElementsByName(old).item(ii);
                obj.id="today";
            }
        }
</script>
</head>
<body>
<table>
    <tr>
        <td id="normal" name="new" onclick="set('new')">Hello</td>
        <td id="today" name="old" onclick="set('old')">World</td>
    </tr>
</table>
</body>
</html>

Answer №1

It is important to note that only one element can be annotated with an ID at a time. Therefore, it is recommended to use classes instead of IDs for annotating elements. Additionally, including a doctype is essential.

Check out the live demo of the corrected code:

<!DOCTYPE html>
<html>
<head>
<style>
.today{
    font-weight: bold;
    color: red;
}

.normal{
    font-weight: normal;
    color: green;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
  var els = document.querySelectorAll('.normal,.today');
  for (var i = 0;i < els.length;i++) {
    els[i].addEventListener('click', function () {
      var els = document.querySelectorAll('.normal,.today');
      for (var i = 0;i < els.length;i++) {
        var currentClass = els[i].getAttribute('class');
        var newClass = currentClass == 'today' ? 'normal' : 'today';
        els[i].setAttribute('class', newClass);
      }
    }, false);
  }
}, false);

</script>
</head>
<body>
<table>
    <tr>
        <td class="normal">Hello</td>
        <td class="today">World</td>
    </tr>
</table>
</body>
</html>

For an easier way to write this functionality, you can also utilize jQuery (demo):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
$(function() {
  $('.normal,.today').click(function() {
    $('.normal,.today').each(function(i, el) {
      var $el = $(el);
      if ($el.hasClass('today')) {
        $el.removeClass('today');
        $el.addClass('normal');
      } else {
        $el.removeClass('normal');
        $el.addClass('today');
      }
    });
  });
});
</script>

Answer №2

You're facing a couple of issues in your code. Firstly, make sure that in your onclick handler, you use "javascript:set" instead of just "set". Secondly, be cautious with parameter names like "in" which is a reserved Javascript keyword. Replace all instances of it with "inv". Once you make these adjustments, your code should start functioning somewhat correctly. Give it a try.

In addition, I recommend working in Firefox and installing the Firebug add-on so that you can easily access the console. This tool will help you identify and troubleshoot similar errors effectively.

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

Unable to retrieve value from defined variable in jQuery and PHP

Hey there, I'm currently facing an issue with getting my PHP variables to be echoed in my JavaScript code. I'm aware that PHP technically doesn't work in JS/jQuery, but I've been exploring different workarounds without much success. Her ...

What is the best way to insert a character (::before) before an element?

I am trying to add a circle/dot using ::before on an element. • • However, I cannot seem to make it visible! .line ::before{ content:'•'; } and .line ::before{ content:'•'; } (Still not showing) I ...

Managing waste: AngularJS service variable cleanup

I am a beginner in angularjs. Recently, I created an angularJS service based on the following diagram: https://i.sstatic.net/NifC5.png The Global Service acts as a way for controllers to communicate with each other. It holds data shared between parent an ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

Using callback functions with Ajax

I'm facing an issue with the code snippet below, within a prototype, where I am trying to pass callback functions (successf, failuref) when creating an instance of Data. Unfortunately, the callbacks don't seem to be triggered. Any assistance on t ...

How to display and download a PDF file on a JSP web page

Can anyone help me with a simple trick to solve this question I have? In my project folder, I have 5 PDF files named file1.pdf, file2.pdf, file3.pdf, file4.pdf, and file5.pdf. I want to display these files in 5 rows on my webpage, each row containing VIEW ...

Utilize jQuery to deactivate all click interactions except for the scrollbar

I am currently working on creating a page that is completely unclickable, both with right and left clicks, and I want to display a message when someone attempts to click. This may lead to some questions such as "Why would anyone want to do this? This s ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

The Fuel-ui module in Angular 2 fails to function properly when loaded from a different directory

We recently switched from ng-cli to Gulp for building our Angular2 project, and we are utilizing Fuel-ui. An unusual error has come up. We have incorporated Fuel-ui's alert component into one of our components. When referencing fuel-ui from node_mo ...

Using JavaScript on an iPhone to automatically launch Safari when clicking on a link from a non-default iOS

When "googlechrome://www.lego.com" is opened in mobile Safari, it switches to the Google Chrome iOS app to open the URL. This feature allows for scriptlets like the following one, which enables you to open the current page in the Google Chrome iOS app from ...

Obscure unidentified attribute within JSON error object

In my node.js console script, I am utilizing pg-promise. Node version: v0.10.38 pg-promise version: 1.1.4 A connection error occurred due to a simple misconfiguration issue that was not very informative. I would like my script to provide a detailed expla ...

Align a div in the center with another div positioned to its left and floated

I am in the process of creating a footer with three components: a logo aligned to the left, a centered navigation menu, and a set of social icons on the right. I have encountered an issue where when I float the logo to the left, the list items within my na ...

Choose a file in React by specifying its path instead of manually picking a file

Is there a way for me to automatically select a file from a specified path into my state variable without having to open a select file dialog? I'm looking for a solution where I can bypass the manual selection process. Any suggestions on how this can ...

Avoiding a jest compile error and executing the test efficiently

Here is my Vue.js code snippet: export default { name: 'App', components: { }, created() { let t = typeof t === 'undefined' ? {} : t; // ISSUE LINE } } The ISSUE LINE runs successfully in the browser without any errors an ...

Exploring JSON with JavaScript

[ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] The data above represents a JSON object. var searchBarInput = TextInput. ...

Having issues delivering static JavaScript files to the client's browser using express.js

I'm looking to create a simple blog application using express.js, where I can write and store posts in a database directly from the browser. After some research, I found the ckeditor package, which allows for formatting before submission. I attempted ...

The form fails to submit even after the validation process is completed

My current dilemma involves the validation of an email and checkbox to ensure they are not empty. Although it initially seemed to work, after filling in the required fields and checking the box, I still receive a warning message (.error) and the form fails ...

Seamless mathematical computations while navigating through Javascript

I have created a basic JavaScript calculator that works efficiently. However, after obtaining the result by pressing the "=" button, I would like the returned result to be saved for future use. The "=" button should be capable of being clicked again to ret ...

Modify the display of multiple divs within a main div

I am facing an issue with a parent div that contains multiple child divs. When there are many children, they all remain in a single row without adjusting into columns. Below is my current HTML: item1 item2 item3 ... <mat-card class="hove ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...