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()
.
Riotjs in latest versions has
Yielding nested HTML
feature. See the API docsIn your case you can easily do that in this way:
In tag definition:
In your app:
Rendered html:
From the docs
The RiotJs Cheatsheet suggests using yield, if I have understood your dilemma correctly.
Main tag declaration:
Child tag declaration:
Main implementation:
If you add an id or name attribute to your inner tag, you can access it via
self
.in js part:
Tested in Riot v2.0.10
Riot only provides 4 properties to access data from the current tag you're in:
See the API docs
edit
Besides this you can directly access
named elements
: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:
won't work, because the DOM is not ready yet. Instead wrap the selector in a 'mount' event listener like this:
https://riot.js.org/api/#-yielding-nested-html
if you have this in your html:
Then in your tag file you can use
<yield/>
This will now make the
<p>
render on the pageSee Tag instance.
We can access to
children
.Also to DOM via
root
.UPDATE - Feb 14, 2015
children
property is obsoleted in Riot.js v2.0.9. The only way to access child elements is usingroot
.