Is it possible to show or hide a DIV based on the text content of another DIV using JavaScript in

I am looking for a way to dynamically hide a DIV based on user roles using only the text inside a title tag as a reference.

Here is an example of the HTML structure:

<title>admin</title>

If the user role is admin, then hide the following DIV:

<div class="demo"></div>.

I must accomplish this task using Vanilla JavaScript only.

One issue I have encountered is that while my current solution successfully hides the div, it briefly shows up during page load:

$('document').ready(
function() {
function _title(){ 
if(document.title=="admin"){
document.getElementById('demo').style.display="none";
}
}
window.onload=_title;
});

Answer №1

Here is a solution to your query. This code snippet will hide the element with the ID of demo.

function _title(){
if(document.title=="admin"||document.title=="admin1"){
    document.getElementById('demo').style.display="block";
}
}
window.onload=_title;

If you want to use class instead of id to make this function work with multiple elements....

function _title(){
if(document.title=="admin"){
    var DemoClass = document.getElementsByClassName('demo');
    for(var i=0; i<DemoClass.length; i++) {
        DemoClass[i].style.display="block";
    }
}
}
window.onload=_title;

If this satisfies your inquiry, it would be great if you could mark it as answered.

Simply include this in your page For id

<style type="text/css">
#demo{display:none;}
</style>

For class

<style type="text/css">
.demo{display:none;}
</style>

---- Titles which have the term Admin ----

For Class

function _title(){
    var allow = document.title.search("admin");
if(allow>-1){
    //Set display for demo element
    var DemoClass = document.getElementsByClassName('demo');
    for(var i=0; i<DemoClass.length; i++) {
        DemoClass[i].style.display="block";
    }
}}

For id

function _title(){
    var allow = document.title.search("admin");
if(allow>-1){
    //Set display for demo element
document.getElementById('demo').style.display="block";
}}

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

Display the duplicated values of an array extracted from a JSON object just once

Having some trouble creating a list from json data, you can check out the example. My goal is to display each value only once if duplicates occur (for example, if there are 2 Martini glasses, I only want one to appear in the list), while still preserving t ...

What is the best way to animate an element when it comes into the user's view

In order to activate the animation of the skill-bars when the element is displayed on the website, I am seeking a solution where scrolling down through the section triggers the animation. Although I have managed to conceptualize and implement the idea with ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

Encountering an error code of 500 when executing the createIndex function in Pouch

I'm currently working on setting up a basic index, and I have the following code snippet: currentDB.createIndex({ index: { fields: ['name'] } }).then((result) => { }).catch((error) => { }) However, when I try to r ...

What is the best way to retrieve a variable in AngularJS1 after the HTML has been divided into multiple child HTML files?

I have segmented my main HTML page into multiple subpages and included them in the main file. However, it seems that each subpage is referencing different '$scope' variables. I am trying to reference ng-modle="My-model" from one subpage to anothe ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

Troubleshooting problem with populating data in Mongoose Database

Here is the code snippet: app.get("/cart", checkAuthentication, function (req, res) { Orders.find({ user: req.user._id }) .populate('user') .populate('order') .exec((err, orders) => { console.log(orders); ...

Compiling with GatsbyJs throws an abrupt token error with 'if' being an unexpected token

I am working on a code snippet in GatsbyJS where I am extracting data from a StaticQuery using GraphQL and then rendering a component. The challenge I am facing is to conditionally check if a specific sub-object exists within the data object, and if it doe ...

Issue with Node's jsonwebtoken library: jwt.sign() method fails to include payload in generated token

I am currently working on developing an API with Node.js and have configured const jwt = require('jsonwebtoken') to handle JWTs. However, I am facing an issue where the generated token does not contain the payload information. To troubleshoot thi ...

What is the best way to automatically log out a user once their session cookie has expired during an online exam?

While developing an MVC ExpressJS Test app, I encountered an issue with auto-logout functionality for users who stop answering test questions. The error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" keeps app ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

Comparison between JavaScript Promise .then(onFulfilled, onRejected) and .then(onFulfilled).catch(errorFunc) in handling asynchronous operations

As I was reviewing promises, I had a question about the order in which the .then/catch calls are executed when using the code below. Are the catch calls being placed at the end of the queue stack? I already have a clear understanding of the distinction bet ...

What is the process for retrieving DOM elements and JavaScript variables using PHP?

I am currently developing a PHP script that will dynamically generate tables in MySQL based on the user's input for the number of columns and column names. However, I have encountered some challenges when trying to access DOM elements and JavaScript v ...

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

Order JSON object based on designated Array

I'm looking to organize a JSON object in a specific order, Here is the current object structure: { "you": 100, "me": 75, "foo": 116, "bar": 15 } I would like to rearrange this object in the following sequence ['me', 'foo', &apos ...

Guide on how to restrict specific days and dates in MUI React datepicker using a JSON array

I am working on a Laravel application that generates a JSON response containing dates and days of the week that need to be disabled in the datepicker. For instance, here is an example of my datesOff constant when I log it: ['2022-05-08', '2 ...

Is it possible to copy text from an iframe to the clipboard?

I have encountered an issue in my React app where I am trying to copy text from a card when the user clicks on it. The app displays multiple cards by looping through an array, so there can be any number of cards (n). The problem arises because the React a ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...