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

Detecting duplicate key values within a JSON array using Angular.js

I am seeking a solution in Angular.js to verify if duplicate key values exist within a JSON array. Below is a breakdown of my code: var result=[{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8dac8b ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...

Invoking a parent controller method from a directive in AngularJS

I have utilized a tree grid plugin from the following link: https://github.com/khan4019/tree-grid-directive and I made some customizations to its template: .directive('treeGrid', [ '$timeout', function($timeout) { return { ...

Creating a Flot Bar Chart that displays non-stacking values

I am new to using Flot for creating charts. Currently, I have a bar chart displayed below: https://i.stack.imgur.com/RSumf.png Here is the code snippet I utilized to generate this chart: $.getJSON('chartBar.json', function(graphDataBar){ $ ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Oh no! "The accuracy of your BMI calculation is in question."

I am currently working on a technical assessment for a BMI calculator, but I am facing a challenge in implementing the formula. The instructions for calculating BMI are as follows: Step 1: The user's height is given in feet, so it needs to be conver ...

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Is it possible to establish communication between JAVA and Javascript using Sockets?

Recently, I developed a Java application that generates some data and saves it in a text file on my computer. Instead of saving this data in a text file, I am looking to send it via Socket. Here is an example: Java public static void main(String argv[] ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

What is preventing Web API from triggering a CORS error in browsers such as Chrome and Edge, as well as the Postman tool?

While working on developing an API in Asp.Net Core 3.1, everything seemed to be functioning properly. However, I encountered CORS-related errors when attempting to send requests via ajax. Interestingly, these errors were not present when sending GET reques ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

Troubleshooting the integration of Text Mask Library with Vue - issue: no export named 'default' available

I was able to implement the vanilla JavaScript version: var maskedInputController = vanillaTextMask.maskInput({ inputElement: document.querySelector('.myInput'), mask: [/\d/, /\d/, '/', /\d/, /\d/, '/ ...

Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user. Table 1 - Story | Table 2 - User api.get('/all_stories', function(req, res) { Story.find({}, function(err, stories) { ...