Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TimiAde's avatar

Appending element in Alpine not working

import Alpine from 'alpinejs';
var $ = require( "jquery" );
// document.addEventListener('alpine:init', () => {
    

Alpine.data('textarea', () => ({
            // open: document.getElementById("textarea").value,
        init() {
			
            console.log("he is  there"), //works
            document.getElementById("textarea").value = "yes" //does not work
            // $('#textarea').html() + '<div class="textarea" contenteditable="true" id="editable"></div>';
        },
        // textarea: '<div class="textarea" contenteditable="true" id="editable"></div>',
        message: '',
        toggle() {
            this.open = ! this.open
        },
        bold() {
            this.message = '<span style="font-weight:bold;">' + this.message + '</span>'
        }
}))

// })

window.Alpine = Alpine;
 
Alpine.start();

Why is console.log working but document.getElement.... not working

0 likes
8 replies
kokoshneta's avatar

So you have <textarea id="textarea"...> in your HTML? Because that’s what you’re looking for: an element with the id attribute of ‘textarea’ – not a textarea element.

Edit: Sorry, I missed the comment that has the HTML code. If it’s a div, it doesn’t have a value property, so document.getElementById('yourDivElement').value doesn’t exist, unless you’ve added a value attribute, which it doesn’t look like you have. A div will instead have an innerHtml property.

1 like
Sinnbeck's avatar

Please show the html that uses this code

1 like
TimiAde's avatar

@Sinnbeck

<div  x-data="formTextarea">
		<div class="wrapper">
			<div class="wrapper-te">
			  <textarea name="" id="textarea" class="" rows="10" x-model="message"></textarea>
			  <div class="textarea" @click="bold" contenteditable="true" @keyup.enter="alert('Submitted!')"  id="editable"></div>
			  <div x-html="message"></div>
			</div>
			 <span x-text="message" class="span"></span>
			 <button @click="bold">bold</button>
		</div>
	</div>
1 like
Sinnbeck's avatar

@TimiAde your js says the data is named textarea but your html says formTextarea. Did you rename it?

1 like
Sinnbeck's avatar

@TimiAde ok. But you want x-model to control the value of the text area but then try to overwrite it with Javascript? Pick one, not both :)

1 like
Sinnbeck's avatar

@TimiAde If you just set message: 'test' does that work? Is is because you need to give it a value from some source?

Please or to participate in this conversation.