Select element by id

Im new to Vue js i need help in selecting an element by ID. i have used v-ref,
ref=“myid” and in “methods” i have accessed it by this.$refs[“myid”]. this doesn’t work and im getting undefined. please help me in this regard.

Help us to help you and share your code, please. Your description is not enough.

if you want to get the element inner content use

v-model="varName"

if you want something else please tell us

thanks for your response. i was looking for vuejs alternative to getElementById and came across v-ref. i used it in the following way
<div id="mydiv" ref="myid"> </div>
and in script
created : function() {
console.log(this.$refs[“myid”])
}
but the value returned is undefined

what you want to do with the element ?

say the element selection is needed for plugin for some operation like zoom. in jquery i would did the same with $(’#id’)

created is run before the component has rendered its DOM, so of course the ref is undefined. Take a look at the lifecycle diagram here.

You want to do this during mounted - at that point, the elements are sure to have been created. If you also want to make sure that those elements have been inserted into the DOM, use a $nextTick callback:

mounted () {
  // elements have been created, so the `ref` will return an element.
  // but the elements have not necessarily been inserted into the DOM yet.
  // you can use $nextTick() to wait for that to have happened.
  // this is espeically necessary if you want to to get dimensions or position of that element.
  this.$nextTick(funciton () {
    console.log(this.$refs.myid)
  })
}
5 Likes

Im able to achieve selection in Mounted. thanks

mounted : function() {
console.log(this.$refs[“myid”])
}

you can use
$(’#id’)
or
document.body.getElementById(‘id’);

normally vue will not prevent this

But as @LinusBorg said

so you need to use Mounted like this :https://codepen.io/anon/pen/POGENp?editors=1111

and this will work even if you’re using normal javascript without any plugins or adds

as i said i was looking for alternative way to acheive the same. as LinusBorg explained i should have used mounted instead of created and it fixed the problem

2 Likes

I am getting this error


even though i am getting whole object after console.log() however can’t assign element to ‘con’ variable


<template>
  <div class="hello">

<head_head></head_head>

</template>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}

div.component {
      border: 1px solid black;
      padding: 30px;
  }
</style>

It’s document.getElementById not document.body.getElementById