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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With