querySelector
Vue is a progressive JavaScript framework for building dynamic user interfaces. Vue’s design is gradually flexible, focusing on declarative rendering and component composition. The core Vue library is focused only on the view layer of the MVC pattern, however, it has a large ecosystem of supporting libraries that make it simple to create responsive web experiences.
Using querySelector
in Vue, we can access and alter the properties of the first selected element, creating dynamic and interactive websites in the process. We can use querySelector
for a variety of reasons, including but not limited to those listed below:
querySelector
is simple to implement inside of Vue code, so it can be used by all levels of developers who are familiar with Vue. In this tutorial, we’ll demonstrate how to get an element within a component using querySelector
in Vue, following step-by-step instructions to access or alter this element property.
To follow along with this tutorial, you’ll need the following:
Note that you can verify your Node.js version by running node -v
in your terminal or command prompt. Let’s get started!
There are several ways to install Vue, however, installing Vue CLI is the simplest. Typically, it is easier to deal with single file components and the Vue API in general. You can install Vue CLI globally by running the command below:
npm install -g @vue/cli
Once installation is complete, you can create a new project with the following command:
vue create my-project
Components allow us to create custom elements that we can reuse across our application as many times as we desire. We can use a component inside another component, making our application dynamic.
querySelector
in VueWe can use querySelector
to select an HTML element that returns the first element within the document that matches a specified selector. It can be used to set, obtain, modify, or delete properties of the selected element in Vue.
Querying the object model of an element in Vue is quite similar to JavaScript’s document.querySelector()
. While we can use document.querySelector()
in Vue as well, Vue components are designed to be reusable and dynamic. Therefore, we can’t ensure an element with a custom className
will be unique.
The querySelector()
function takes one parameter that is used to get a specified element. This parameter can be a tag name, class name, or ID of the HTML element. The syntax for the querySelector()
function is as follows:
this.$el.querySelector("input").value = "Enter name"
Note that this.
can only be used inside a Vue component.
this.$el.querySelector
in VueThe $el
option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this.$el.querySelector
is used to access HTML elements and modify the element’s properties.
this.$el.querySelector
follows the syntax below in a Vue component:
this.$el.querySelector(parameter).value;
Unlike this.$refs
, this.$el.querySelector()
does not require you to add the ref
attribute to your HTML tag element to access the element. You can access the element directly using its tag name, class name, or ID.
We’ll use this.$el.querySelector
inside a component to access HTML elements and change some of the elements’ properties.
Let’s select an HTML element tag inside a component and change the text of the element to “you clicked the button”. We’ll set its text color property to pink by using the tag name to access the element:
<div id="app" > <span >{{ message }}</span> <button @click="myFunctionClick()">Click Here</button> </div> </body> <script type="text/javascript"> new Vue({ el: '#app', data: { message:"You clicked me" }, methods:{ myFunctionClick: function () { this.$el.querySelector("span").innerText = ' you clicked the button'; this.$el.querySelector("span").style.color = 'pink'; } } }); </script>
When you click on the button, the text color of the span element should change to pink.
The element can be selected through its ID by passing the ID name into the querySelector
method. To demonstrate, let’s create a hidden text page with a button called show hidden text. When the button is clicked, the text will display and set the button to hidden
. We’ll use the code below:
<div id="app" > <span hidden id="hide" ></span> <button id="bn" @click="myFunctionClick()">show hidden text</button> </div> </body> <script type="text/javascript"> new Vue({ el: '#app', data: { message:"You clicked me" }, methods:{ myFunctionClick: function () { this.$el.querySelector("#bn").style.display = 'none'; var hide = this.$el.querySelector("#hide"); hide.innerText = 'this is the hidden text show time'; hide.style.display = 'block'; hide.style.color = 'pink'; } } }); </script>
When you want to apply multiple properties on the selected element, you can store this.$el.querySelector()
in a variable.
We can also get elements by class name using querySelector
just like we did for the tag and ID. Let’s demonstrate by creating a simple application that will allow the user to insert a URL from the input element. The image will be displayed in an img
HTML element:
<body> <div id="app" > <img src="" class="image"> <input type="url" class="urlinput"> <button id="bn" @click="myFunctionClick()">Load image</button> </div> </body> <script type="text/javascript"> new Vue({ el: '#app', data: { Message:"load image" }, methods:{ myFunctionClick: function () { this.$el.querySelector(".image").src = this.$el.querySelector(".urlinput").value; } } }); </script>
In the code above, the this.$el.querySelector(".image").src
property is used to change the image src (URL). The value obtained from the specified input element is assigned to the selected img
element.
When an element is selected using the querySelector()
function, the properties of the selected element can be obtained or changed. There are many properties querySelector()
supports, like autofocus on input elements, accessing an element’s text using innerHTML
, element styling, and more.
As an example, we’ll use the code below from our previous code:
this.$el.querySelector(".image").src ="logo.jpg"
Let’s change the image src of the selected image class name to logo.jpg
:
this.$el.querySelector(".image").src
The code above is used to get the property (URL) value of the selected image ID, which we can store in a variable. Let’s use querySelector
to set autofocus on the input
element:
this.$el.querySelector("input").focus
If there are two or more elements with the same tag name, class name, or ID, and querySelector
is used to access the element, only the first element will be accessible. Let’s demonstrate this using the following sample:
<body> <div id="app" > <img src="" class="image"> <span>first element</span><br> <span>second element</span> <br> <button id="bn" @click="myFunctionClick()">change background color</button> </div> </body> <script type="text/javascript"> new Vue({ el: '#app', data: { message:"You clicked me" }, methods:{ myFunctionClick: function () { this.$el.querySelector("span").style.backgroundColor ="red"; } } }); </script>
We can see from the code above that when the button is clicked, only the first span element’s background color changes to red.
In this tutorial, we learned how to access elements inside a component in Vue application using querySelector
. We can also access each element using its tag name, class name, or ID. Now, you should be able to make your webpage more dynamic and interactive. I hope you enjoyed this tutorial.
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps, including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
One Reply to "Getting an element within a component with Vue <code>querySelector</code>"
I have been using jQuery for a long time and I still love it. But VUE JS works a little differently and this way reminds me of jQuery approach. I dont see benefits in your examples. Why edit or search for anything in this jQuery way? It’s easier at VUE JS.