WoJ
WoJ

Reputation: 29987

How to get an Element by Id in Vue?

I would like to get an outer Element in Vue, using 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>

This brings me an empty Element, but not a null - which suggests that the query was partially successful (something was found).

This is actually a POC for a more general problem I face: the ability to get an outer Element (say, a container div) from within a Vue component (this brings me a null, which the documentation says to be the response when the element was not found).

Is it possible, from within a Vue object or component, to query an outside Element present in the DOM?

Upvotes: 6

Views: 35095

Answers (3)

ericobi
ericobi

Reputation: 549

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>

I think your code is working now and you are getting dom in helloElement.

result

Adding .innerHTML you will get the solution.

Upvotes: 0

user6748331
user6748331

Reputation:

It is possible, as you can see. But be warned, that if you want something like this, your app is probably bad designed and you created entry poin for XSS attack.

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>

Upvotes: 6

mrogers
mrogers

Reputation: 1217

Here is a snippet accomplishing what I believe you want to do. I modified your example to use classes since I wanted to avoid having two elements with the same id. I'm just using outerHTML to get the DOM element as a string and then rendering it using Vue's v-html.

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>

Upvotes: 1

Related Questions