Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the contents of an element?

Tags:

vue.js

I use VueJS to set the content of elements via data defined in a Vue instance:

<p id="hello">
    {{ message }}
</p>

How can I completely replace the content of such an element (discarding the previous content, in the case above {{ message }}), to turn the <p>into for instance

<p id="hello">
     The replacement text
</p>

In jQuery I would have called $("#hello").html("the replacement text"); - what is the equivalent in VueJS?

like image 875
WoJ Avatar asked Oct 24 '16 07:10

WoJ


People also ask

Is used to replace elements content?

The most common approach to replace the content inside an element is with the innerHTML property. Alternatively, you can use the textContent to set the element's text content, which is considered safe against XSS attacks.

How do you replace an element with another?

First, select the DOM element that you want to replace. Then, create a new element. Finally, select the parent element of the target element and replace the target element by the new element using the replaceChild() method.

How do I change the content of a div?

Set the innerHTML Property of an Element to an Empty String and Insert a new Child Text Node to the Element. Another way to replace the text in a div is to set the innerHTML property to an empty string. Then we can add a new text node and insert it into the div. div.

How do I change text in a div element?

Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content. Here is the HTML for the examples in this article.


1 Answers

Vue is MVVM so you map data to the view. You can replace HTML with v-html, but your html would have to be stored in your vm and this isn't recommended:

HTML:

<div id="app">
  <span v-html="message"></span>
  <button v-on:click="newHtml">Change HTML</button>
</div>

Javascript:

new Vue({
  el: "#app",
  methods: {
    newHtml() {
      this.message = '<p style="color:red;">New Message</p>';
    }
  },
  data: {
    message: "<p>Message</p>"
  }
});

Heres the JSFiddle: https://jsfiddle.net/e07tj1sa/

Really, with vue you should try to move away from thinking in jQuery, they are conceptually different. In vue the preferred method is to build up your app with reusable components not to directly affect the html in the DOM.

https://vuejs.org/guide/components.html#What-are-Components

like image 126
craig_h Avatar answered Sep 28 '22 12:09

craig_h