Retrieve the element by its Id for precise targeting on a particular webpage

I'm new here and looking for some assistance, so please help if you can :)

I'm working on a web page but encountered an issue that I hope you can help me solve. Here are the 3 files involved:

  1. home.html --> Main page
  2. login.html --> Page with a form to be opened in an iframe within home.html
  3. hh.js --> JavaScript file

My goal is to display the user's name instead of "Login" on home.html after they press submit on the login.html page.

For now, I'm just trying to change the word "Login" to something else temporarily instead of using the actual username.

Here is the code from hh.js (JavaScript file):

function goback(){
alert("yes") 
var str = document.getElementById("demo").innerHTML;
var res = str.replace("Login","ppap");
document.getElementById("demo").innerHTML = res;
}

Below is the code snippet from home.html where the word "Login" appears:

<a onclick="login()"><span id="demo">Login</span></a>

And here is the full code from login.html:

<html>
<head>
<script language="javascript" src="hh.js">
</script>
</head>
<body bgcolor="#000033">
<br><font color="white">
LOGIN<br>
USERNAME:<input type="text" id="user"><br>
PASSWORD:<input type="password"><br>
<button onclick="goback()">Submit</button>
</body></font>
</html> 

Issue-

I have the function goback() in both files just for testing purposes. Both pages have buttons (submit button on login.html && random button on home.html with the same function).

When I click the button on login (iframe in home.html), the alert pops up saying "yes" but doesn't change the "Login" text. However, when I click the button on home.html with the same function, the alert appears and the text changes to "ppap".

I think the problem is that the getElementById search is looking for the id in login.html instead of home.html.

If anyone can help me target getElementById to home.html, I would really appreciate it. Please provide a simplified code as my school teachers might not understand complex codes. Additionally, any other simple methods to achieve the same result quickly would also be helpful like hiding the area until the login function is called and then triggering the goback() function on the same page.

Answer №1

If the element with the id "demo" does not exist, JavaScript will be unable to locate it and apply any text. To resolve this issue, consider placing the desired text within a div or span element:

<span id="demo">LOGIN</span>

It is important to note that "Login" and "LOGIN" are not considered identical in JavaScript. Therefore, if you attempt to replace "Login", the action will fail as there is no match. However, replacing "LOGIN" will produce the desired outcome.

var res = str.replace("LOGIN","ppap");

An alternative solution would be:

var res = "ppap";

Additionally, remember to include a semicolon after each line of code in your JavaScript function calls. A semicolon was missing in the provided code snippet.

Answer №2

You should have the following ready:

function login() {
    document.getElementById("demo").innerHTML = "Logout";
}

In order to modify the text within

<a onclick="login()"><span id="demo">Login</span></a>

Your question is a bit hard to decipher, but for displaying an element, you can try

JavaScript

document.getElementById("demo").style.display = "block";

CSS

#demo {display: none;}

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

Revamping password security using token-based password reset system

As I work on the password reset feature for my authentication application, I have decided to utilize JWT, node.js, and express. Here's my approach: First, the user enters their email, triggering the generation of a token that is then sent to the user& ...

Is it possible to update the content within an HTML paragraph without deleting the existing span elements

Check out this code snippet below from jquery UI, showcasing an alert box: <div class="ui-widget"> <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"> <p><span class="ui-icon ui-icon-alert" style="float: le ...

Implementing a tooltip or bubble display functionality without using the span tag or title attribute

Is there a way to display tooltips when users hover over specific text or keywords? The text is retrieved directly from the database, so adding span or div tags or title information is not an option. Are there any methods to automatically generate tooltips ...

In Nodejs, the function 'require' fails to load a module when using specific filenames

Hello everyone, I am a long-time user but this is my first time asking a question. So, I have a file named file.js where I am trying to require another file called user.service.js at the beginning of the file: var userService = require('./user.servi ...

Difficulty encountered when attempting to implement custom filtering based on condition in HTML using Angular

I'm still new to angular, so please bear with me if this question seems trivial. I have a collection of integers in my controller and I need to filter it to only show items that meet a certain condition. Initially, I attempted the following: <div ...

How to position an SVG image directly next to text

Here is my JSFiddle with an SVG positioned to the left of some text inside a button. I am looking for a way to align the SVG vertically with the text within the button. I've considered a couple of methods: Trying to adjust the line-height, but that ...

Modify the dropdown menu title dynamically based on the selection made in Angular

My Angular web-application has a dropdown menu that looks like this: <div class="btn-group" dropdown> <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN <span class="caret"></span>&l ...

The Ajax request functions flawlessly on Mozilla but encounters issues on Chrome, causing confusion as it occasionally works

I am using a PHP file with a class and function to store data in the database, accessed via AJAX. While everything works smoothly in Mozilla, Chrome seems to be causing some issues. Strangely, sometimes it works fine, but other times it fails for no appare ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

What is the reason for being unable to remove the event listener from a sibling element?

function show1() { console.log("ok1"); document.getElementById("a2").removeEventListener("click", delegate); } function show2() { console.log("ok2"); } function show3() { console.log("ok3"); } function delegate(event) { var flag = event.target ...

Issue with symbol not rendering correctly in Email Body when setting width to '100%' in Postman

I'm currently working on sending emails using APIS in NodeJS. The issue I am facing is related to the CSS code with '%' symbols triggering errors when attempting to send the email via Postman, resulting in a 500 error. However, removing the ...

The error was thrown at line 800 in the loader.js file of the internal modules

When I ran yarn install in my project folder, I encountered the following error: internal/modules/cjs/loader.js:800 throw err; ^ Error: Cannot find module 'ts-node/register' Require stack: - internal/preload ?[90m at Function.Module._resolveF ...

Setting up webRTC and Express.js to function within the same domain requires proper configuration

Currently, I am in the process of creating a video conferencing website using node.js and express.js rather than apache. However, I am faced with some challenges when deciding on the best approach. The main goal is to have the server deliver the website t ...

Customizing the angular ng- tags input plugin: A step-by-step guide

Encountering an issue with the ng-tags input autocomplete feature when attempting to display a duplicate name. When entering "R" in the input box and two instances of "rob" are present, the following error occurs: Duplicates in a repeater are not allowed. ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to ...

Issue with JavaScript: Required accessToken parameter missing in ReactJS

Issue with Contentful.js When running a React project using `npm start`, an error related to `contentful.js` is displayed. Why does this package show these errors? I have attached the error screenshot for reference. How can I resolve this issue? .env fil ...

Error: The module could not be found due to an inability to resolve the parsed request

I am working on a project that uses class components as a requirement by the company, and I cannot switch to function components. After running elint --fix and restarting the project, I encountered an error that is specific to just one file. The error me ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

Validating Age Using jQuery UI Datepicker

Creating a dating platform for users over the age of 18, I am utilizing jQuery UI datepicker. To ensure only individuals above the age of 18 can register, I need the YEAR section to display 18 years earlier (1997) instead of the current year (2016). This w ...