Evgenij Reznik
Evgenij Reznik

Reputation: 18614

Access String after binding

I made an application with jQuery Mobile. The page is divided into several sections, as described here: Adding Pages in jQuery Mobile.
In the second section, that acts as an own page, some text comes from a database using data-bind:

<div class="myClass" data-bind="text: MyText"></div>

The text appears, but no string operations are possible, I simply can't access it.

With:

console.log(document.getElementsByClassName("myClass").innerHTML);

I get undefined.

I assume this is because the data-binding occurs after console.log is executed.

How can I access the string?

Upvotes: 0

Views: 32

Answers (3)

Roy J
Roy J

Reputation: 43899

The string is in your viewmodel in the variable MyText. The whole point of Knockout is that you don't reach into the DOM to get at your data. It's in your viewmodel and the DOM merely reflects it.

Upvotes: 0

Jose Luis
Jose Luis

Reputation: 994

I think youre using a div tag but you should use a input tag:

 <input data-bind="value: MyText" />

If you only want to see the value of the observable 'MyText', you shouls look in your viewmodel. Here you have an example.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337700

getElementsByClassName returns an array of DOMElements. If you're sure there's only one you can hard-code the array accessor:

console.log(document.getElementsByClassName("myClass")[0].innerHTML);

Example fiddle

Upvotes: 1

Related Questions