Search code examples
javascriptvue.jsgsap

How to find child element with the help of parent's ref?


I need to access items using vue's this.$refs but not sure how to achieve it. I don't want to use jQuery for this.

<template>
  <div>
    <svg ref="svgItem">
      <path d="M899.33,118.33h-81.7v90.2h-31.3V2.07h31.3v88.5h81.7V2.07h31.29V208.53H899.33Z" />
    </svg>
  </div>
</template>

<script>
import { TimelineLite } from 'gsap';

export default {
  mounted() {
    const { svgItem } = this.$refs;
    const timeline = new TimelineLite();
    timeline.to(svgItem, 5, { opacity: 0.3 });
    // timeline.to('${svgItem} > path', 5, { opacity: 0.3 }); // something like this :)
  },
};
</script>

I know how to do it with jQuery:

const svgPath = $('#parent path');
// or may be with:
const svgPath = $('#parent').find('path');

I kinda feel that I may end up with querySelector but not sure how to mix and match variable and string:

const { svgItem } = this.$refs;
const selector = document.querySelector(svgItem > 'path')  // something like this :)

const timeline = new TimelineLite();
timeline.to(selector, 5, { opacity: 0.3 }

Thank You.


Solution

  • Method querySelector is also on HTML Element. It's not only available on document.

    const { svgItem } = this.$refs;
    const svgPath = svgItem.querySelector('path');