What would cause this to result in a blank array?

I have a main component that contains multiple sub-components, which I navigate between by clicking on different elements. These sub-components are all Vue files.

What I am trying to achieve is to dynamically highlight the active component when it is being used.

For example:

When I click on the Home button in the navigation bar, the component switches to the Home sub-component (which is already working), and I want to add a border around it to indicate it as the active tab.

To do this, I planned the following steps:

1) Get a collection of all the clickable elements

2) Filter out the element with a specific data attribute (which determines the active component)

3) Apply CSS styling to the active element

Here is the code snippet from the parent component (I've omitted some CSS for brevity):

<template>
  <div id="grid">
    <nav id="navbar">

      <ul id="nav">
        <a href="#" class="Home" @click="current = 'Home'" ><li>{{navbar.Home}}</li></a>        
        <a href="#" class="Reservation" @click="current = 'Reservation'" ><li>{{navbar.Reservation}}</li></a>
        <a href="#" class="About-us" @click="current = 'About-us'" ><li>{{navbar.About}}</li></a>
        <a href="#" class="Contact" @click="current = 'Contact'" ><li>{{navbar.Contact}}</li></a>
      </ul>

      <div class="button"> <!-- Make some animation of this button becomes an extendable window of signing up. Don't forget  -->
        <a href="#">Sign Up
        </a>
      </div>
      <img src="https://i.pinimg.com/564x/8b/fa/5d/8bfa5d6a52a03e83b995fec69a4d8c2c.jpg" alt="" id="logo">
    </nav>      

    <main id="content"> 
      <keep-alive>
        <transition name="component-fade" mode="out-in">
          <component v-bind:is="current"></component>    
        </transition>      
      </keep-alive>        
    </main>      

    <footer>
      <p>Copyright © All Rights Reserved</p>
    </footer>
  </div>
</template>

<script>
import Home from "./components/Home.vue";
import Aboutus from "./components/About us.vue";
import Contact from "./components/Contact.vue";
import Reservation from "./components/Reservation.vue";
import Signup from "./components/Signup.vue";

export default {
  components: {
    Home: Home,
    "About-us": Aboutus,
    Contact: Contact,
    Reservation: Reservation,
    Signup: Signup
  },
  data() {
    return {
      navbar: {
        Home: "Home",
        Reservation: "Reservation",
        About: "About us",
        Contact: "Contact"
      },
      current: "Home"
    };
  },
  methods: {}
};
let nodeList = document.getElementsByTagName("a");
console.log(nodeList);
let active = Array.from(nodeList).filter(
  element => element.className == this.data.current
);
console.log(active);
active.style.cssText = "border-bottom: 5px solid #5fb0e4;";
</script>

The issue I'm facing is that the array returns empty and the style isn't applying. Can anyone provide assistance on this problem?

Answer №1

Encountering a similar issue. When using Vue templates and scripts, you're essentially building a virtual DOM. Vue operates differently than your expectations. Here's a suggestion to try:

...
export default {
  ...
  data() {
    return {
      navbar: {
        Home: "Home",
        Reservation: "Reservation",
        About: "About us",
        Contact: "Contact"
      },
      current: "Home"
    };
  },
  methods: {},
  // This method (lifecycle hook) runs
  // after the Virtual DOM you created from template is patched into the Browser DOM
  mounted () {
    let nodeList = document.getElementsByTagName("a");
    console.log(nodeList);
    let active = Array.from(nodeList).filter(
      element => element.className == this.data.current
    );
    console.log(active);
    active.cssText = "border-bottom: 5px solid #5fb0e4;";
  }
};

By following these steps, your array will no longer be empty. However, it doesn't achieve much. Vue doesn't recognize that you modified the Browser DOM, leading to your changes being overwritten during the next DOM patching. It seems like you haven't grasped the core concept of Vue yet. It would be beneficial for you to delve deeper into Vue principles.

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

What is the best way to insert space between spans in HTML when designing email templates?

I am currently designing email templates, which means I have some limitations. Although I have used align="center", I still require some spacing between the two spans. How can I achieve this? CODE: <td width="659" height="28" bgcolor="#999999" align= ...

Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error. I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handlin ...

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

The combination of VUEJS 3 composition computed and vuex does not exhibit reactivity

I am currently working on a website using Vuejs3 with the composition api and incorporating VUEX 4 for state management. As part of this project, I am setting up the login functionality which is functioning perfectly. However, I am facing an issue with the ...

Top strategies for avoiding element tampering

What is the best solution for handling element manipulation, such as on Chrome? I have a button that can be hidden or disabled. By using Chrome's elements, it is possible to change it from hidden/disabled to visible/enabled, triggering my click functi ...

Encountering Rendering Issues with EJS Post HTML Conversion

After working on a much larger project for over a month, I'm now six hours into troubleshooting and everything is starting to blend together. Prior to switching to EJS, everything was working perfectly. I'm not looking for someone to solve the ...

Tips for setting up a grid where boxes have a consistent width but varying heights to maximize space utilization

Seeking design inspiration from Pinterest, where fixed width columns are used but each grid item fills all available space with varying heights. Check out this example: https://i.sstatic.net/i2WDo.jpg Initially considered using flexbox for this layout, b ...

Determine the total number of selected items in MagicSuggest when it loses focus

I have been working with MagicSuggest and I am currently facing an issue where I need to retrieve the length of selections on a blur event. Interestingly, my code functions perfectly fine when a new selection is added using the ENTER key, but it fails when ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

TinyMCE removes the class attribute from the iframe element

I am trying to specify certain iframes by using a class attribute to adjust the width using CSS. The iframes I am working with are google maps embeds, similar to this one: <iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0 ...

Creating dynamic image carousels using the latest versions of Bootstrap and AngularJS

I have created an array that stores various images using angularJS: $scope.docImg = [ '../../Content/Image/BackGrounds/abra.png', '../../Content/Image/BackGrounds/background_black.jpg', '../../Content/I ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

Separate the elements with a delimiter

I am in the process of inserting various links into a division by iterating through a group of other elements. The script appears to be as follows $('.js-section').children().each(function() { var initial = $(this).data('initial'); ...

Obtaining the value of an input field in HTML

I am currently working on a text input field that triggers a JavaScript function when a numeric value is entered. <input type="text" value="key" ng-keypress="submit(key)" ng-model="pager.page"/> Controller $scope.submit = function (val) { ...

What are the most effective strategies for creating cross-platform components using Vue.js 2.0?

In my current project, I am looking to create a universal component library using Vue.js 2.0 that can be seamlessly integrated across various platforms. The focus of this query lies in establishing the most effective styling practices for components. Typi ...

Is there a way to prevent HTML code from being executed when sharing it as text? I want to be able to share code without it being activated as HTML on the page

Seems like I have a straightforward issue related to HTML tags. I am looking to post some code snippets on my blog, specifically the <h1> heading</h1>. I want visitors to view and not just the bolded text of heading. Do I need to incorporate J ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

Bizarre Drop-down Peculiarities

Having a perplexing issue where the 'search' list item is oddly shifted below the dropdown box only when it is displayed. The other list items remain in their correct positions. Any advice on how to resolve this? The appearance and functionality ...

Find the most recent date in a file and display the line associated with it

I am working with a document named Application.txt that consists of multiple columns and rows as shown below: ApplNo DocsURL DocDate 4782 www…. 7/28/2003 4782 www…. 11/23/2008 4782 www…. 3/24/2012 5010 www…. 4/5/2003 5010 ww ...

Guide to appending the chosen item from a search bar to a fresh array using vue3 js

Does anyone know how to resolve the issue I'm facing with adding selected items from a dropdown list to a new array and displaying them on the page? Currently, I have added an onblur event to the input field to hide the dropdown when clicked outside, ...