htmlvue.jskenticovue-directiveskentico-kontent

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


I am developing a website using VueJS, and Kentico Kontent as a CMS. This CMS offers the "rich text" feature, basically allowing text content to embed links and basic formatting, which gets automatically converted into HTML when served through the API.

I have no problem displaying the HTML content using the v-html directive, but I cannot think of a way to set the attributes of the inner <a> tags to _blank, so that the embedded links open new windows when clicked.

Is there any elegant way to do this without having to parse the HTML from the Front-end?


Solution

  • 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>