Why is it difficult to delete elements from the DOM in VueJS?

As a newcomer to VueJS, I find myself struggling with some basic tasks. One particular challenge I'm facing is trying to manipulate an SVG element on my webpage, such as deleting the children of a <g> element and replacing them with new ones. Despite numerous attempts, nothing seems to work and I am at a loss.

Let's take a look at a simplified version of the code...

HTML

<svg id="hz_svg" data-name="hz_svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000">
  <g class="scale" width ="1400" style="fill: none; stroke: white; stroke-width: 2px;"> 
    <line x1="100" y1="1000" x2="1500" y2="1000"  />
    <g class="ticks">
      <line x1="100" y1="1000" x2="100" y2="980"/>
      <line x1="800" y1="1000" x2="800" y2="980"/>
      <line x1="1500" y1="1000" x2="1500" y2="980"/>
    </g>
  </g>
</svg>

App.js

const ticksEl = document.querySelector("#hz_svg .ticks");

createApp({
  methods: {
    renderTicks() {
      ticksEl.replaceChildren();
      console.log('REMOVED!!!');
    },

The interesting part here is that even though console.log('REMOVED!!!') is executed, indicating that ticksEl.replaceChildren() ran successfully, the elements on the page remain unchanged. The svg <line>s within ticks are not removed. It's worth noting that this issue does not seem to be related to the JavaScript itself, as placing replaceChildren() outside of createApp works perfectly fine for removing the elements.

So, why am I unable to remove these elements? What could be causing this unexpected behavior?

Just to clarify, I prefer not to store the line elements within the VueJS data unnecessarily.

Note: Upon running console.log(ticksEl.children) after console.log('Removed!!!'), it shows no lines (children), even though they are still visible on the page.

Answer №1

If you're interested in achieving something similar to the example below, it's recommended to first learn more about Vue and other related frameworks:

new Vue({
  el: '#container',
  template: `<div>
<button v-on:click="removeShapes">Remove Shapes</button>
<label><input type="radio" name="fill" value="red" v-on:change="saveFill" :checked="currentFill === 'red'"> Red</label>
<label><input type="radio" name="fill" value="blue" v-on:change="saveFill" :checked="currentFill === 'blue'"> Blue</label>
<label><input type="radio" name="fill" value="green" v-on:change="saveFill" :checked="currentFill === 'green'"> Green</label>
<button v-on:click="addShape">Add Shape</button>
  <svg id="hz_svg" data-name="hz_svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="1600" height="1600"  preserveAspectRatio="xMinYMin slice">
  <template v-for="shape of this.shapesHTML">
    <g v-html="shape" />
  </template>
</svg>
</div>`,
  data: {
    shapes: [
      { type: 'circle', cx: 30, cy: 50, r: 30, fill: 'red' },
      { type: 'circle', cx: 70, cy: 50, r: 30, fill: 'green' },
      { type: 'circle', cx: 110, cy: 50, r: 30, fill: 'blue' },
    ],
    currentFill: 'red',
  },
  computed: {
    shapesHTML() {
      return this.shapes.map((shape) => {
        let attributes = (({ type, ...attributes }) => attributes)(shape)
        let htmlAttributes = Object.entries(attributes).map(([key, attribute]) => `${key}="${attribute}"`)
        return `<${shape.type} ${htmlAttributes.join(' ')} />`
      })
    }
  },
  methods: {
    removeShapes() {
      this.shapes = []
    },
    addShape() {
      this.shapes = [ ...this.shapes, {
        type: 'circle',
        cy: 50,
        cx: 20 + ((this.shapes.length + 1) * 30),
        r: 30,
        fill: this.currentFill,
      } ]
    },
    saveFill(e) {
      this.currentFill = e.target.value
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="container"></div>

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

The TextInput field is not displaying my placeholder text - what could be causing this issue?

I am facing an issue where the placeholder is not appearing on both <TextInput> elements, and when the user inputs something, it does not show up in those <TextInput> boxes. I need to understand why this behavior is occurring. Below is the con ...

What is the best way to retrieve the chosen option when clicking or changing using jQuery?

CSS <form name='category_filter' action='/jobseek/search_jobs/' method='get'> <select id="id_category" class="" name="category"> <option value="" selected="selected">All</option> <option v ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...

Fixed Positioning Div to Stay at the Top while Scrolling

Currently, I have successfully implemented the functionality to stick the div to the top once it scrolls down by 320px. However, I am curious if there is an alternative approach to achieving this effect. Below is the code snippet I am using: jQuery(functi ...

Tips for importing a PDF file and storing it in your database

I have a project using Angular 7, .NET Framework, and MongoDB where I am creating user profiles. One of the requirements is to allow users to optionally upload a PDF file along with their other information. This is what I have implemented so far: <labe ...

Experiencing an excessive number of requests while managing the display of a spinner through axios interceptors

I have a single page application built with Vue (Webpack) where I am trying to manage the visibility of a spinner based on whether the app is currently processing an HTTP request or response. After following some tutorials, I implemented the event bus pat ...

Receiving an unknown value from the input field

I can't seem to retrieve the value of my input, as quantityElement.Value consistently returns undefined. Here is the section of my HTML and JS that I am struggling with. In my JavaScript function, the quantityElement always gives me an undefined whe ...

Implementing Dynamic FormControl Values within FormGroup in Angular: A Step-by-Step Guide

GenerateFields(customControl, customValue): FormGroup { return this.fb.group({ customControl: new FormControl(customValue), }) } I am looking for a way to dynamically add the value of customControl from the parameter passed in the Ge ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

Automatically populate the article number field once the article name has been entered

I am currently working on a HTML <form> using PHP. Within this form, there are three <input> fields. The goal is to have the second <input> field automatically populate once the first one is filled out. This will involve triggering an HTT ...

Setting up an i18n project in AngularJS

I just embarked on my angularjs journey yesterday with little to no prior knowledge about it. My initial goal is to centralize all the labels for my UI in a file (to facilitate swapping them out for i18n). As far as I know, this can be achieved by importi ...

Struggling to access the height attribute from a CSS file

Hey there. I'm pretty confident that the solution to my query is quite simple. So, I have a .css file with this particular code snippet: div.site { text-align:center; border:2px solid #4b6c9e; padding:1px; margin-top:10px; font-size:medi ...

When working in three.js, it's important to remember that geometry.faceVertexUvs[0][0][index] does not equate to geometry.vertices

From what I gather, the uv coords ("texels") of each vertex in a mesh can be accessed using: geometry.faceVertexUvs[ materialIndex ][ faceIndex ][ vertexIndex ] The issue I'm facing is that the vertexIndex seems to have a different mapping order com ...

Are there any issues with the function that is preventing me from creating a user in mongodb?

Hello, I am having trouble adding a user to MongoDB and displaying all the user's information on the screen. The user's location information is stored in the Locations Schema, but I am unsure how to retrieve this information (such as city, town) ...

Displaying subsets of data based on the identifier of the primary array

In my JSON file, I have an array containing various categories and their respective subcategories. { "Women": [ { "id" : 1, "name" : "See All", &q ...

Bootstrap and jQuery for creating columns of equal height

I'm currently utilizing Bootstrap in a web project and struggling to dynamically set the same height for column elements. I am aware of the .row-eq-height class, but using it compromises the responsiveness of Bootstrap elements. My goal is to ensure t ...

Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling. The issue arises when I input text into the textarea and hit enter for a new line. ...

Button react-native press following textInput within scroll view aware of keyboard movements

I'm currently facing an issue where I have a TextInput and a button nested inside a KeyboardAwareScrollView. The goal is for the user to input some text and then tap the button created using TouchableOpacity, which should send the inputted text forwar ...

How can you make nested JSON values optional in Joi Validation?

As I work on my API, I encounter a nested JSON structure that serves as the payload for the endpoint. Here is an example of what it looks like: {"item_id":"1245", "item_name":"asdffd", "item_Code":"1244", "attributes":[{"id":"it1","value":"1"},{"id":"it2" ...

What could be causing this highchart plot to fail to display in both IE and Chrome?

Check out the plot in this jsfiddle: http://jsfiddle.net/essennsee/y5HCm/ The plot looks good in Firefox, but only shows the legend in IE and Chrome. If I remove the following code snippet it works fine. Is there a different way to format the labels?: ...