Outputting HTML with functions

I have a function that returns HTML code.

renderSuggestion(suggestion) {
    const query = this.query;

    if (suggestion.name === "hotels") {
        const image = suggestion.item;
        return this.$createElement('div', image.title);
    } else {
        let str = suggestion.item.name;
        let substr = query;
        return this.$createElement('div', str.replace(substr, `<b>${substr}</b>`));

    }
},

However, the <b> element is not rendering as an HTML element in the browser. It is being displayed as a string... How can I make sure the <b> element is displayed correctly?

Thank you

Answer №1

The reason why your HTML tags are appearing as-is when you provide a string as the second argument of the createElement method in VueJS is because VueJS interprets it as a text node. To fix this, you should pass a data object as the second argument to have better control over the properties of the created element. Check out the official documentation on render functions for more details:

this.$createElement('div', {
    domProps: {
        innerHHTML: str.replace(substr, `<b>${substr}</b>`)
    }
});

Remember to be cautious when using innerHTML and avoid inserting user-provided HTML code to prevent XSS attacks.

Answer №2

You have the option to create a component and utilize v-html for displaying the output.

Define props for your inputs:

export default {
  props: {
    suggestion: Object,
    query: String
  }
};

Then, include a template that incorporates your logic within the template section

<template>
  <div class="hello">
    <div v-if="suggestion.name === 'hotels'">{{suggestion.item.title}}</div>
    <div v-else>
      <div v-html="suggestion.item.name.replace(this.query, `<b>${this.query}</b>`)"/>
    </div>
  </div>
</template>

This approach offers more flexibility when working with intricate layouts.

Check out a functional example here

Answer №3

Can you please elaborate further on why it is not displaying? Feel free to include a picture for better clarity. You might want to try applying a custom CSS class to troubleshoot the issue.

.custom-bold {
    border-style: solid;
    font-weight: bold;
}

After defining the "custom-bold" class, make sure to use it instead of just "b".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to Send Data Back to Parent Popup Window

Is there a way to achieve the following functionality with jQuery: create a popup window that sends a value back to the main window when a link in the popup is clicked, then closes the popup and automatically submits a form in the main window based on the ...

Can the contents of a JSON file be uploaded using a file upload feature in Angular 6 and read without the need to communicate with an API?

Looking to upload a JSON file via file upload in Angular (using version 6) and read its contents directly within the app, without sending it to an API first. Have been searching for ways to achieve this without success, as most results are geared towards ...

Display a particular div when a specific image is present within another div

I'm currently working on a task, but I'm having trouble with it. If I have an image called smiley.png within a div with the class "selected." <div class="selected" style=""><img width="25" height="24" src="images/smileys/smiley.png ...

CKEditor with Readonly Option and Active Toolbar Controls

In my current Rails project, I have successfully set up a CKEditor instance in readOnly mode. Everything is functioning as expected. Now, I am attempting to add a custom plugin button to the toolbar while keeping the textarea in readOnly mode. After some ...

Leverage ng-value attribute when working with radio buttons in AngularJS

I have recently started working with AngularJS and I am trying to create a selection using radio buttons that will save as a boolean value. However, when I use ng-value, the value saved in the database is null. Here is the HTML code: <label><in ...

Collect user input from an array of checkboxes

After spending hours attempting to retrieve data from an array of checkboxes with the same name, I am still facing difficulties. <input type="checkbox" name="node"/> var selectedValues = []; $(document.getElementsByName("node")).each( ...

Personalized cursor that blinks while utilizing window.history.replaceState

While navigating between sub-pages, I utilize the window.history.replaceState method to replace URLs in my web application. However, I have noticed that my custom cursor briefly blinks (replaced by cursor: default) when the current URL is replaced with a n ...

Does IE 9 support endless local storage capacity?

I recently updated my HTML5 persistent storage (localStorage) capacity testing to address a memory exception issue in the previous version. I even created a jsFiddle showcasing it: http://jsfiddle.net/rxTkZ/4/ The testing code involves a loop: var val ...

Navigate to the vite Frontend by utilizing the domain specified in the /etc/hosts file

When I was on node v16, I could easily set up my hosts file like this: #/etc/hosts 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost 127.0.0.1 my-domain.test and then access the site through my-domain.test:{port} Howeve ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

Sending information between children components in VueORTransferring data between

So, I have a question regarding the Authentication section of my application. Within my application, I have various components and routes, including register and login. The register functionality is working properly with the API, storing both the usernam ...

I am experiencing an issue with the initial for-loop in my code as it is not

Upon clicking the start button, the score button, as well as the try again or correct button, are not being updated. Can someone help me figure out what's wrong? I believe the issue lies within this section of the code: for (i=0; i<5; i++) { do ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

retrieve the parent frame's request URL

I am faced with the task of writing a JSP code that retrieves the getRequestURL() of the parent frame (the URL shown in the address bar) from a child frame. However, when I attempt to do this, I only obtain the URL of the child frame. Is there anyone who ...

What is the best approach to sending numerous queries from a single endpoint using Express?

I am attempting to perform multiple database queries and create an object that stores each response from the database in a specific field. Below is the code I have written: router.post('/search', (req, res) => { var collection = db.get(). ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

What is the best way to divide a string that contains n concatenated JSON strings in JavaScript or Node.js?

Imagine I receive the following string from a socket server (which is out of my control): {"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} Because it contains 2 JSON strings, using ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...