Tips for accessing an Element by its Id in Vue

I am trying to access an external Element in Vue by using the method getElementById():

new Vue({
  el: "#vue",
  data: {
    helloElement: document.getElementById('hello')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="hello">
  hello
</div>
<div id="vue">
  {{helloElement}}
</div>

Although this code provides me with an empty Element, it doesn't return a null, indicating that the query was partially successful (something was found).

This is essentially a proof of concept for a larger issue I am dealing with: the ability to retrieve an external Element (such as a container div) from within a Vue component (which results in a null, as per the documentation's explanation when the element is not located).

Is there a way, from inside a Vue object or component, to access an external Element present in the HTML DOM?

Answer №1

Yes, it is indeed possible to achieve this. However, it is important to note that implementing such functionality may indicate poor app design and could potentially create a vulnerability for XSS attacks.

new Vue({
  el: "#vue",
  data: {
    helloElement: document.getElementById('hello').outerHTML
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="hello">
  hello
</div>
<div id="vue" v-html="helloElement"></div>

Answer №2

Here is a code snippet that achieves the desired functionality. I made some changes to your original code by using classes instead of ids to avoid duplication. I utilized the outerHTML method to extract the DOM element as a string and then displayed it using Vue's v-html directive.

new Vue({
  el: "#vue",
  data: {
    helloElement: document.getElementsByClassName('hello')[0].outerHTML
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div class="hello">
  hello
</div>
<div id="vue">
  <div v-html="helloElement"></div>
</div>

Answer №3

Creating a new instance of Vue:
new Vue({
  el: "#vue",
  data: {
    helloElement: document.getElementById('hello')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="hello">
  hello
</div>
<div id="vue">
  {{helloElement.innerHTML}}
</div>

It seems like your code is functioning properly now, and you are successfully capturing the DOM element in helloElement.

https://i.sstatic.net/qKqsZ.png

By adding .innerHTML, you will be able to access the solution you're looking for.

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

Sending the value from a for loop through AJAX and populating it into a form field

Currently, I have implemented a piece of JavaScript code that captures user input, sends a request to an endpoint using AJAX, and appends a specific field from the returned results as an option within a datalist. This functionality is working perfectly fin ...

I'm unable to provide an ID value within the modal section

<div class="table"> .... <tr *ngFor="let product of products; index as i"> <th scope="row">{{ i + 1 }}</th> <td>{{ product.name }}</td> <td>{{ product.category }}</td> <td> ...

Permission Denied when trying to use a non-root user in PNPM docker command

Today, I came across pnpm and it successfully resolved the issue I was facing with npm timing out during installation, which is absolutely fantastic. However, I encountered a problem with pnpm when using it in a docker image. In the past, when using npm, ...

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

What is the best way to include icons in a list item on the left, center, and right side?

I'm in the process of developing an Ionic app that integrates with the Spotify API. One feature I want to include is a widget that displays three icons in a list item: the left icon for the last song, the center icon for play/pause functionality, and ...

Nuxt is unable to modify the data variable

When working with Vue in Nuxt, I often encounter an issue where changes to a variable in the data section of my component do not reflect in the HTML. For example: export default { data () { return { openPopup: '1' } }, methods: ...

Alert: Attempting to invoke the setState method on an unmounted component

While running unit tests with Jest, I encountered a warning when attempting to change the setState input value. The warning message says: "Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in you ...

I'm confused as to why I keep receiving alert messages every time I click on a button. Can someone please provide

My aim is to enhance the functionality such that clicking the blue button changes the reading status to either <Yes> or <Not>. Any guidance on this would be greatly appreciated. Additionally, I am puzzled as to why, currently, I receive an aler ...

Guide on deactivating a button when a numerical value is detected within a field in VUE JS

I need help figuring out how to automatically disable a button when a field contains a number. Here is an example of my code: disabledSubmitButton() { return this.$v.$error || this.firstName === '' || this.lastName === '' || ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

Where is the function returned by redux-thunk invoked?

Can you help me understand where the function returned by addUser is being called in this action creator and redux thunk function? const userAdded = () => ({ type: types.ADD_USER, }); export const addUser = (user) => { return function (dispat ...

What is the best way to restrict the maximum number of items stored in local storage?

I'm creating a GitHub search app using the GitHub API in Angular. I want to restrict the number of items that can be stored in local storage. If the number of stored elements exceeds 5, the "Add to Favorite" button should either stop working or disapp ...

Numerous jQuery pop-up windows are being generated instead of just one as intended

When I load an editing form asynchronously on my web page using jQuery.get and display it within a jQuery dialog, multiple instances of the div that I apply .dialog to are unexpectedly being appended to document.body. Here is the code snippet for loading: ...

When the back button is clicked, what happens in Next.js?

Currently, I am facing an issue with maintaining the scroll position on a page when a user navigates back using the browser's back button. The situation involves a list component displaying products, allowing users to scroll down and view all items. U ...

I am having trouble with $(this) in my jQuery click event handler

When I click my function, I want to change a parent element that contains this function. However, $(this) is not working. What could be the issue? function accountConfirm(message, title, yes_label, no_label, callback) { console.log($(this)); $(&qu ...

How to manipulate a jade element with JavaScript

How can I capture the value of an input tag in real time and store it in a JSON object? In my Jade file, this is what it looks like: extends layout block content h1 todos #task <input type="text" id="task" name="task"/> #todos for todo ...

Adding fields from one collection to another collection in MongoDB based on specific conditions for a considerable amount of data

I encountered a situation where I constantly need to update a large number of collections. Here are the collections: coll1 { "identification_id" : String, "name" : String, "mobile_number" : Number, "location" : String, "user_properties" : [Mixe ...

Activate link by checking the 'Accept' box

I am trying to add a 'Click to Accept Terms' checkbox on my website (), which will activate a link to another page once checked. After modifying a script and HTML code that has been successful elsewhere on the internet (as seen in this JSFiddle ...

Determining the navigation changes within a React browser

Hi there, I'm using browserHistory.goForward() and browserHistory.goBack() to navigate forward and backward in my app with arrow buttons. However, I need a way to determine if the route has actually changed after executing browserHistory.goForward/goB ...

A guide on tallying up the occurrences of a boolean value within a map

The Angular 8 framework is being utilized. Within an array named teams, the length can be accessed using teams.length. Each entry in the teams array contains a nested map called teamInfo. Within this map, there is a boolean value isClosed that can ...