Exploring Techniques to Control the DOM Using VUE Attributes and Variables

I am working on a simple component that displays an HTML string:

<template>
  <v-list-item-content v-html="html_string">
</template>

<script>
  export default {
    name: "HtmlRenderer",
    props: ['html_string']
</script>

The HTML content is fetched from an API in the parent component and may include basic HTML elements such as <p> and <blockquote>.

I want to manipulate the DOM of this HTML string by performing the following actions:

  1. Locate each <blockquote> tag and insert a button before it (there could be zero or more instances)
  2. Create a button that toggles the .active class for the corresponding <blockquote>

How can I achieve these steps within the lifecycle of a VUE component? Is it possible to call a function defined in the methods section of the component from the injected <button>?

Any insights or suggestions would be greatly appreciated.

Answer №1

Here are some suggestions to tackle this challenge:

  • Instead of directly updating the html string before parsing, consider manipulating the DOM using vanilla JS after the component is mounted.
  • Utilize Vue's render function within your component to customize its rendering process.
  • While the render function approach may be powerful, it can also be quite complex and challenging.

In order to proceed, you could follow these steps:

  1. Take on the task of parsing the html string yourself to break it down into individual html tags.
  2. Iterate through each tag and use the render function to display it accordingly.
  3. For instances where you encounter a blockquote, incorporate the necessary button element.

interface HTMLTag {
   name: string,
   attributes: any[],
   childrens: HTMLTag[],
}

render (h: CreateElement) {
    const parsedElements: HTMLTag[] = parseToHTMLTag(this['html_string'])
    
    parsedElements.forEach((tag) => {
       if (tag.name === 'blockquote') {
           renderButton()
       }

       renderTag(tag)
    })

    renderTag = (htmlTag: HTMLTag) => {
       return h(tag.name, {
          attrs: tag.attributes,
          childrens: render(tag.childrens)
       })
    }

    renderButton = () => {
       return h('button', { ... })
    }

}

This concept can be implemented with effort and determination. However, be prepared for a substantial amount of work ahead. Best of luck!

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

What strategies can I use to reduce duplication in my HTML and JavaScript code?

Struggling with messy HTML and JS code? If you're using Bootstrap-3 and jQuery-1.11.0, dealing with dropdowns might be tricky. Especially when it comes to switching icons based on the dropdown state and ensuring only one dropdown is open at a time. Is ...

Using jQuery to target adjacent elements excluding those that are separated by other text

I have been attempting to locate and combine adjacent em tags within paragraphs, but it has proven to be a more challenging task than I initially anticipated. Let's explore some examples to illustrate this issue: <p><em>Hello</em>&l ...

Using 2 parameters, ExternalInterface.addCallback

Attempting to pass 2 variables from JavaScript to Flash, I came up with a solution in ActionScript 3 to try and receive them. ExternalInterface.addCallback("callAs", muscle, tension); However, this method resulted in an error: Error: 1137 - Incorrect nu ...

Adjusting the bottom property to a negative value in CSS will stretch the page downwards

I want to hide a portion of an HTML element at the bottom of the page and then reveal the entire element by sliding it upwards upon clicking with the help of CSS3 transitions. The expected behavior is for the part of the element extending below the page t ...

Show variable outside callback function - Ionic2

When working with ionic2, I encountered a situation where I needed to pass a variable from an asynchronous method to my template and other methods within the component file. In the `ngOnInit` method of my controller, I have the following code: ngOnInit() ...

Creating an object in javascript with two arrays: a step-by-step guide

Looking for help with merging two different object arrays: array1 = [Object, Object, Object] array2 = [Object, Object, Object] Each Object in array1 has the structure: {property1 : "somevalue"} While each Object in array2 follows this structure: {prop ...

The jQuery selector threw an Uncaught SyntaxError due to an Unexpected identifier

Just starting out with programming, I'm attempting to send data using my Python script. I'm unsure of what the error message is indicating. $(document).ready(function() { $("tags").keyup(function({ var search = $("tags").val() $.post(" ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

Creating nested routes in react-router is a useful technique for managing complex applications. By

I have a parent container with nested routes: function Home() { render ( <Router> <Switch> <Route exact path="/website" component={Website} /> <Route path="/dashboard" compo ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Web audio: setTimeout slows down when mobile screen is turned off

In response to Yogi's feedback (refer to the discussion on "setTimeout" and "throttling" in https://developer.mozilla.org/en-US/docs/Web/API/setTimeout ), I attempted to enhance performance by integrating an AudioContext. document.addEventListener(&ap ...

Exploring Chrome's WebUSB Functionality with AngularJS

Recently, I encountered a challenge while utilizing WebUSB APIs for Chrome through AngularJS. This particular project involves accessing an esc/pos thermal printer for the purpose of printing invoices. In typical JavaScript: HTML: <button id="connect ...

tips on assigning a unique ID to an item in a firebase database collection

My code is structured like this: const userCollectionRef = collection(db, 'users'); Then I add data using the following method : const addInfoToDataBase = async () => { checkLike(); await addDoc(userCollectionRef, { likePost: us ...

Objects within an array are not sorted based on their properties

I'm currently struggling with sorting an array of objects based on a specific property. Despite my efforts, I can't seem to figure out what's causing the issue as it remains unsorted. Would appreciate some assistance. You can take a look at ...

Issue with server-side rendering due to importing routes

After researching SSR with React, I came across various approaches but found one example that seems more suitable for my web app built on React/GraphQL/Apollo/Express/Webpack. However, I am facing an issue. Here are some code snippets: server.js ... ...

What is the process for conducting a comprehensive match search using dual parameters?

I am working with a database model Schema({ members: [ { type: String, required: true, ref: "User" } ], createdAt: { type: Date, default: Date.now(), required: true }, lastMessage: { message: { typ ...

"Is there a specific way to designate the content type as multipart form data when using Axios

I am experiencing difficulty with axios as I am unable to set the content type to multipart/form-data. Below is the code snippet: function (config) { // Do something before request is sent const isLogin = authService.isLogin(); if (isLogin) ...

Changing the text of a link when hovering - with a transition

Seeking a straightforward way to change text on a link upon :Hover. I desire a gentle transition (text emerges from below) and fallback to default if JavaScript is disabled. HTML <div class="bot-text"> <a href="">Visit this site</a> ...

The attribute on the label fails to trigger any action on the linked input upon clicking, due to the binding of the id and for

My component is designed to display a checkbox and label, with inputs for id, name, label, and value. Here's the code: <div class="checkbox col-xs-12" *ngIf="id && name && label && value"> <input type="checkbox" ...

Developing a HTML button through Javascript that triggers a method with a single parameter when clicked

My current project involves creating HTML buttons through JavaScript using AJAX. Each time I click one of these buttons, it triggers an AJAX function. If the AJAX request is successful, it retrieves a number that will be utilized in a for loop. As the loop ...