[Vuejs]-How can I set the "target" attribute of <a> tags which are already "embedded" into HTML?

4👍

You could create a directive:

Vue.directive('links-in-new-window', {
  inserted: function(el) {
    const anchors = el.querySelectorAll('a')

    anchors.forEach((anchor) => anchor.target = "_blank")
  }

})

And just apply that to the same element you’re using the v-html on:

<div class="content" v-html="content" v-links-in-new-window></div>

0👍

In vue V3 the directive would look like this:

app.directive('links-in-new-window', {
  mounted: function(el) {
    const anchors = el.querySelectorAll('a')
    anchors.forEach((anchor) => anchor.target = "_blank")
  }
})

HTML is the same, remember to use v- => v-links-in-new-window

<div class="content" v-html="content" v-links-in-new-window></div>

Leave a comment