Exploring VueJS: Accessing Dom Attributes

How can I retrieve the href attribute when a button is clicked?

<a v-on:click.prevent="func($event)" href="/user/all/2">
    <i class="fa fa-edit"></i>
    <span>Get Data</span>
</a>

JavaScript File (main.js)

new Vue({
el: 'body',

methods: {
    func: function (event) {
        element = event.target;

        console.log(element); // Output : Select span|i|a element

        href = element.getAttribute('href');
    },
}
});

The target event does not select the a element. It selects the clicked element instead.

Answer №2

Vue emphasizes the use of reusable components, which is known as the "Vue way". To implement this approach, you need to create a component first:

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <my-comp></my-comp>
</div>

<script>
  // Define and register the component
  Vue.component('my-comp', {
    template: '<div>Just some text</div>'
  })

  // Create a new Vue instance
  new Vue({
    el: '#app'
  })
</script>

Next, you can add custom attributes to the component and access their values:

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <my-comp my-attr="Any value"></my-comp>
</div>

<script>
  Vue.component('my-comp', {
    template: '<div>aaa</div>',
    created: function () {
      console.log(this.$attrs['my-attr']) // Accessing custom attribute value from $attrs object
    }
  })

  new Vue({
    el: '#app'
  })
</script>

Answer №3

var obj = {
  method: function(event) {
    console.log(event.currentTarget.id); //retrieves the entire html tag
    console.log(event.currentTarget.href); //displays the href value
  }
}
// Objects  
var new_obj = new Vue({
  data: obj,
}).$mount("#new_obj");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="new_obj" v-cloak class="card">
  <a v-on:click.prevent="method" href="/user/all/2">
    <i class="fa fa-edit"></i>
    <span>Fetch Data</span>
  </a>
</div>

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

Turn off the ability to view the content of .css and .js files within the browser

Earlier, I inquired about how to disable file and folder listing and discovered that it can be achieved using a file named .htaccess. To disable folder listing, I entered Options -Indexes in the .htaccess file located in the parent folder. Additionally, to ...

Determine if a Vimeo video successfully loads within an iframe using jQuery

I'm currently working on a form where users input a Vimeo video ID and the page displays a preview of the video in an iframe. How can I verify if the video exists? This is the JavaScript code used to load the iframe: $(document).on('change ...

Building an Angular 4 universal application using @angular/cli and integrating third-party libraries/components for compilation

While attempting to incorporate server side rendering using angular universal, I referenced a post on implementing an angular-4-universal-app-with-angular-cli and also looked at the cli-universal-demo project. However, I ran into the following issue: Upon ...

Error message: "Oops! Looks like the Mix manifest is missing in Laravel Vue.js setup

https://i.sstatic.net/SaNUi.png I recently set up my Laravel-Vue application on a cPanel server. However, whenever I make changes and upload the app.js file to the server, the browser's cache history doesn't seem to refresh automatically. I find ...

Multiple loop in Node.js with Selenium

I just completed a node script using selenium webdriver for automated testing purposes. Below is the code snippet: var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until, _und = require('unders ...

Finding the common dates between two date arrays in Node.js

Looking for help with correctly intersecting matrices while working in nodejs? Trying to compare two arrays to find common elements, also known as an "array intersection." This seems to be a common question, and despite trying various solutions mentioned o ...

The input box fails to show larger values on the user's page

Show me the biggest number that the user enters in an input box and then display it back to them. I need some improvements to my code, ideally making it possible with just one input box instead of two. <!DOCTYPE html> <html la ...

Embracing right-to-left (RTL) languages

I am looking to create a website that can support both left-to-right (LTR) and right-to-left (RTL) languages seamlessly. My goal is to have the text direction switch automatically to RTL if the content is in an RTL language. Additionally, I want the input ...

Nuxt prevents the importing of client-side scripts during server-side rendering

Within my nuxt.js application, I encounter a dilemma with a script that relies on an NPM package designed exclusively for browser environments (utilizing elements such as document, location, window, etc.) Is there a strategy to specifically exclude this s ...

Using CSS transition on the height property does not produce the desired effect

I'm currently working on a menu interaction that activates on click. Here is the code snippet for reference: let btn = document.querySelector('.trigger'); let icons = document.querySelector('.icons'); let labels = document.query ...

JavaScript allows users to input an array name themselves

When fetching rows from my database using AJAX, I transform them into an array with a variable identifier. Here is the PHP code: $query_val = $_GET["val"]; $result = mysql_query("SELECT * FROM eventos_main WHERE nome_evento LIKE '%$query_val%&apos ...

What is the best way to incorporate the 'autoskip' functionality into chartjs?

Click here for an example I've been attempting to utilize the autoSkip functionality outlined in the documentation for chart.js: Visit this link for more information on autoSkip The current issue I'm facing is that my x-axis labels are o ...

When using Angular's ng-repeat, data binding may not work properly for arrays that are created dynamically

I've encountered a bug that I've been trying to troubleshoot with various solutions from StackOverflow, but nothing seems to work, such as: 1) Using $rootScope Array. 2) Implementing $scope.$apply() (after realizing it's not ideal due to a ...

Creating a versatile function for rendering content

I am working on a unique calendar feature that involves using checkboxes for filtering purposes. So far, I have managed to get all the filters functioning correctly by triggering my render event in this manner: //Initiate render event when checkbox is cli ...

"Displaying Undefined Content when an Incorrect Value is Added, but functioning correctly with the right

I am attempting to populate the HTML table below with data from a JSON file: When I set var i = "0";, I receive undefined, but changing it to var i = "dv"; results in nothing being displayed. I am uncertain of the error I am making and what is causing th ...

Tips on how to toggle the class of one specific element without affecting others

Whenever I click on a div, it expands. However, if I click on a collapsed one, both collapse and the first one returns to an inactive state. At this point, the last two are in both active and inactive states. And if at this time I click on the first one, t ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

The issue of numbers not being properly summed in Node.js

I'm currently working on storing product prices in sessions. The issue arises when a product is clicked twice - instead of adding the two prices together, they concatenate into a single value. For example, 15 + 15 results in 01515. I'm unsure why ...

The equivalent of ESM for resolving modules using the `createRequire` function with a specified

In the process of developing a JavaScript instrumentation engine, I am currently focused on traversing a source file's Abstract Syntax Tree (AST) and queuing imported modules for instrumentation in a recursive manner. In order to achieve this, it is c ...

Prevent scrolling in AngularJS model popups

When loading data for the first time in a model popup, the scroll bar is not displayed inside the popup. However, after performing a search function and filtering the data, the scroll bar appears inside the model popup. How can this issue be fixed? this ...