Getting an element within a component with Vue querySelector
Wednesday 22 December 2021 05:02 PM Beirut Time · 673
Wajdi Alkayal Wajdi Alkayal
Getting an element within a component with Vue 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:

  • Add or remove a selected element’s CSS style
  • Retrieve or set the value of a selected input element
  • Get or set the attribute of a selected element

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.

Prerequisites

To follow along with this tutorial, you’ll need the following:

  • Node.js ≥v10 installed
  • npm v≥6.7 installed
  • Familiarity with Vue

Note that you can verify your Node.js version by running node -v in your terminal or command prompt. Let’s get started!

Installing Vue

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

Vue components

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 Vue

We 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 Vue

The $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.$refsthis.$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.

Getting an element by tag

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.

Getting an element by ID

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.

Getting an element by class

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.

Wrapping up

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>

&lt;/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.

Conclusion

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.

Experience your Vue apps exactly how a user does

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, 
Related Posts
Graphic design
09 June
The Power of Email Marketing
03 June
Photography
01 June