Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access child elements within riot.js

If I have a custom riot tag with a p in it like this:

<custom>
  <p>This is a text</p>
</custom>

How do I access the <p> element from within the <custom> tag?

Update: I've received a whole bunch answers that are of ways to select it from the DOM. What I want is a way to select the inner p tag from within the component library riot.js itself. I'm looking for a more riotjs specific answer. For example with polymer you use this.$.content.getDistributedNodes().

like image 229
ThomasReggi Avatar asked Jan 30 '15 23:01

ThomasReggi


3 Answers

See Tag instance.

We can access to children.

customTagAndLoops = this.children

Also to DOM via root.

iAmDom = this.root
childNodes = this.root.childNodes
p = this.root.querySelector('p')

UPDATE - Feb 14, 2015

children property is obsoleted in Riot.js v2.0.9. The only way to access child elements is using root.

like image 50
Tsutomu Kawamura Avatar answered Nov 16 '22 12:11

Tsutomu Kawamura


Riot only provides 4 properties to access data from the current tag you're in:

  • this.opts
  • this.parent
  • this.root
  • this.tags

See the API docs

edit

Besides this you can directly access named elements:

<my-tag>
  <p name="foo">Hi, I'm foo</p>
  <script>
    console.log(this.foo);
  </script>
</my-tag>

see the docs

/edit

There's no direct reference to any of the elements you defined in your custom-tag; the rest comes down to just pure old JS (which you might favour or not).

Like others stated, you can access elements using dom methods. However, in some cases you need to wait until the DOM is actually loaded. For instance:

<my-tag>
  <p>yada</p>
  <script>
    console.log(this.root.querySelector('p'))
  </script>
</my-tag>

won't work, because the DOM is not ready yet. Instead wrap the selector in a 'mount' event listener like this:

<my-tag>
  <p>yada</p>
  <script>
    this.on('mount', function() {
      console.log(this.root.querySelector('p'))
    })
  </script>
</my-tag>
like image 40
publicJorn Avatar answered Nov 16 '22 11:11

publicJorn


If you add an id or name attribute to your inner tag, you can access it via self.

// with 'id'
<custom><p id="pTest">Test</p></custom>

// with 'name'
<custom><p name="pTest">Test</p></custom>

in js part:

self = this

self.pTest
>>  <p id=pTest>Test</p>

Tested in Riot v2.0.10

like image 28
Federico Elles Avatar answered Nov 16 '22 11:11

Federico Elles