var parent = el.getParent();
parent.getElement('div[class=test]'); // return array
var parent1 = el.parentNode;
parent1.getElement('div[class=test]'); // error getElement is not a function
It seems parent1 doesn't have all element methods of MooTools, how to extend all element method of parent1, like in page
Note: I have to use parentNode.
parent.getElement('div[class=test]');
should really be
parent.getElement("div.test");
there's a substantial difference going to element.getParent() and element.parentNode - it boils down to Element prototype, which cannot be extended in old versions of IE.
mootools works around that by saving a reference to the methods directly on the elements instead as properties.
hence if you do element.getParent() and that returns an element, this will extend it to have all the prototypes. element.parentNode returns a simple element object, which will work in browsers where the Element.prototype is inherited correctly.
you can make the second method work in IE by doing:
var parent1 = el.parentNode;
$(parent1).getElement("div.test");
Subsequent references to parent1 do not need the $ (or document.id) as the element will already have been extended.
so to summarize the answer:
to make an element extended, you need to run it through a selector.
var parent = el.parentNode;
$(parent); // this extends it.
parent.getElements("div.test").something()
Both ways work just fine on an element, proof: http://jsfiddle.net/SuJn6/
I assume what you're doing wrong is your el is actually an Element Collection, not a single element. In which case you need to loop your first array, and only then use parentNode, example: http://jsfiddle.net/35Fxf/
Pro-tip: name your variable carefully, el and els - all makes a huge difference.
Related
The component that I have testing renders something this:
<div>Text<span>span text</span></div>
As it turns out for testing the only reliable text that I have is the 'span text' but I want to get the 'Text' part of the <div>. Using Jest and react-testing-library I can
await screen.findByText(spanText)
This returns an HTMLElement but it seems limited as I don't have any of the context around the element. For example HTML methods like parentNode and previousSibling return null or undefined. Ideally I would like to get the text content of the parent <div>. Any idea how I can do this with either Jest or react-testing-library?
A good solution for this is the closest function.
In description of closest function is written: Returns the first (starting at element) including ancestor that matches selectors, and null otherwise.
The solution would look like this:
screen.getByText("span text").closest("div")
Admittedly, Testing Library doesn't communicate clearly how to do this. It includes an eslint rule no-direct-node-access that says "Avoid direct Node access. Prefer using the methods from Testing Library". This gives the impression that TL exposes a method for a situation like this, but at the moment it does not.
It could be you don't want to use .closest(), either because your project enforces that eslint rule, or because it is not always a reliable selector. I've found two alternative ways to tackle a situation like you describe.
within():
If your element is inside another element that is selectable by a Testing Library method (like a footer or an element with unique text), you can use within() like:
within(screen.getByRole('footer')).getByText('Text');
find() within the element with a custom function:
screen.getAllByText('Text').find(div => div.innerHTML.includes('span text'));
Doesn't look the prettiest, but you can pass any JS function you want so it's very flexible and controllable.
Ps. if you use my second option depending on your TypeScript config you may need to make an undefined check before asserting on the element with Testing Library's expect(...).toBeDefined().
But I have used HTML methods a lot and there was no problem yet. What was your problem with HTML methods?
You can try this code.
const spanElement = screen.getElementByText('span text');
const parentDiv = spanElement.parentElement as HTMLElement;
within(parentDiv).getElementByText('...');
I have a script called equal-heights.js which works together with underscore.js. It equalize the divs to the size of the highest div with an animation (optional). The problem is that when I charge the page nothing happens, it starts to equalize the divs only when I resize the browser.
The initialising code on the HTML:
$(document).ready(function() {
$('.profile-panel').equalHeights({
responsive:true,
animate:true,
animateSpeed:500
});
});
You can see the equal-heights.js here: http://webdesign.igorlaszlo.com/templates/js/blogger-equal-heights-responsive.js
What should I do so that, when the page loads, the animation starts to equalize the divs automatically?
I created my own test and realized the issue is with the way the plugin has been written, namely that it only accepts one value for the class name, otherwise it will break.
This is because of the following line in the script:
className = '.'+$(this).prop('class');
What this does is that it takes the class property of your element and adds a dot (.) in front; a nice but not very scalable way of getting the current selector, because if you have multiple class names, it will only put a dot in front of the first one, so if you have...
<div class="profile-panel profile-panel-1st-row profile-panel1">
...it will transform it into...
$('.profile-panel profile-panel-1st-row profile-panel1')
...so understandably this will not work properly, as the dots are missing from the rest of the classes.
To go around this, until version 1.7, jQuery had a .selector property, that however has now been deprecated. Instead they're now suggesting to add the selector as an argument of your plugin's function as follows (and I tailored it to your situation):
First define an option called selector when calling the function:
$('.profile-panel-1st-row').equalHeights({
selector:'.profile-panel-1st-row',
// ...
});
Then setup the className variable inside the plugin as follows:
var className = options.selector;
Another thing you can do is the place the class you're using to activate the plugin as the first one for each element you want to use it on, so instead of...
<div class="profile-panel profile-panel-1st-row profile-panel1">
...do this...
<div class="profile-panel-1st-row profile-panel profile-panel1">
...then you can setup the className variable inside the plugin as follows:
var className = '.'+ $(this).prop('class').split(" ").slice(0,1);
This basically splits the class names into parts divided by space and takes the first one.
To have the best of both solutions, simply set className to the following:
var className = options.selector || '.'+ $(this).prop('class').split(" ").slice(0,1);
As to the animation, it only works on resize; that is intended, that's how the plugin has been built, you can play around with the original example of the plugin creator that I added to jsfiddle: http://jsfiddle.net/o9rjvq8j/1/
EDIT #2: If you're happy to change the plugin even more, just remove $(window).resize(function() in the if(settings.responsive === true) check and you'll have it working. ;)
if(settings.responsive === true) {
//reset height to auto
$(className).css("height","auto");
//re initialise
reInit();
}
So, I'm trying to access the input field hidden deep within a paper input field. This is so that I can change the input type and so on. After inspecting the element, You can see that it has 2 shadow roots as explained in this blog. However, the method explained in that blog no longer works. I'm using dart version 1.5.3, polymer 0.12.0-dev.
I try to query the paper input like so:
querySelector('#paper-input-id').shadowRoot.querySelector('#input');
However, that returns null. This is because the shadowRoot property only returns the first shadow root. The input field is buried in the second shadow root. I guess what I am asking is if there is a generic way to select the nth-shadow root of an element?
This seems exactly how I did it in the unit test for <core-input>
var input = dom.document.querySelector("#changeAndInputEvent") as CoreInput;
var domInput = (input.shadowRoot.olderShadowRoot.querySelector('#input') as dom.InputElement);
what also should work is
var domInput = (dom.document.querySelector("#changeAndInputEvent /deep/ #input");
or
var domInput = (dom.document.querySelector("* /deep/ #changeAndInputEvent /deep/ #input");
when the paper-input itself is inside a shadow-dom
Instead of using shadowRoot and olderShadowRoot, which may change if for whatever reason paper-input decides to inherit something new that then inherits from core-input, try using the more generic shadowRoots map (note the 's'):
querySelector('#paper-input-id').shadowRoots['core-input'].querySelector('#input');
To set the html of elements on my site, I use mostly
$('elementId').innerHTML = "<p>text</p>";
Looking through the mootools docs, I found this example given:
$('myElement').set('html', '<div></div><p></p>');
Is there any difference between these? Should I go through and change .innerHTML to the mootools method, or doesn't it make a difference?
the reason why the first one works is because - as it stands - a $ selector (document.id) in mootools returns the actual element. this - in normal browsers - is identical to document.getElementById() and the element object exposes any and all of its attributes/properties for you to edit.
the problems with NOT using .set are:
when mootools 2.0 aka MILK gets released, it won't work as it will be wrapped like jQuery and the selector won't return the object (mootools is becoming AMD hence it won't modify native Types - Element, Array, Number, String, Function(maybe!) - prototypes).
you cannot chain this. with set you can: $('someid').set("html", "loading...").highlight();, for example.
set is overloaded - it can set either a single property or multiples by means of passing an object. eg, element.set({html: "hello", href: "#", events: boundObj});
look at https://github.com/mootools/mootools-core/blob/master/Source/Element/Element.js#L936-942 - you can pass an array as an argument and it will join it for you, this makes it easy to work with multi-line strings and ensures performance in IE
edit: the BBT fan has kind of opened a separate topic: should the framework try to block you / prevent you from doing things that break the browser?
if you want to, you can add disallowed elements by changing that setter Element.Properties.html.set = function() { var tag = this.get("tag"); ... check tag }; - isn't mootools great?
mootools - by default - will NOT try to prevent you from doing stupid shit [tm] - that's your responsibility :) try setting height on an element to a negative value in IE, for example. should the Fx class prevent you from doing that? No. Should the setter prevent you? No. The footprint of constant checks to see if you are not breaking means it will slow everything down in performance-critical cases like animations.
I have a container that holds map of elements.
class MyContainer{
.....
Map<String,MyElement> elements = new ...
...
}
Each element has name property. The key in the map is the element's name. i.e. the method insert is as follows:
void addElement(MyElement elem){
elements.put(elem.getName,elem);
}
I need to use the map data structure, because I have many read operations based on the element name.
The problem is that I need to support modification of the element's name. Changing element name must derive changes in the map. (insert the element with a new key otherwise I won't be able to find that element)
I have thought about two options:
add setName method to MyElement class that will update the container that its name was changed.
don't add setName method to MyElement class, add rename element method to the container, the container will be in charge of updating both the element name and the key in the map.
Option 1 means I have to maintain reference from each element to the container. (this part of the program should maintain low memory footprint).
What do you say? do you see a better option?
I would fire a property change notification on the setName method of the element and handle it in the container object which is listening that notification.
First of all, note that if MyElement can conceivably be used in a context without MyContainer, then option 1 is out.
MyContainer has an obvious relation with MyElement, since its code references MyElement instances through its map. The reverse is not true: the code in MyElement does not need to reference MyContainer. So option 2 is better.
Perhaps, though, you could go for a third hybrid option:
MyElement has a rename method that only changes its own name, and MyContainer has a rename method which calls MyElement.rename and moves the object in the map to the new key.
If the element is only used in this container.
Put the rename operation on the container.
Make the rename method on the element private so another programmer can't accidentally change just the element and forget to update the container.
Option 2 is the simplest and most efficient, thus my choice.
Clearly you know that, so what's the dillema?
Another option is to make a MyString class, that will serve as both a std::string AND a reference to MyContainer. MyString's modifying methods would be in charge of re-maping, and you'd still have a low footprint. E.g.:
class MyString;
class MyElement {
...
MyString name;
...
};
MyContainer * aContainer = new MyContainer;
new MyElement(MyString("Yaron Cohen",aContainer), ...); /* MyString need to be explicit only upon MyElement construction. takes care of inserting into container. */
...
MyElement * someElement = aContainer["Yaron Cohen"]; /* just std::string for lookup */
someElement->name = "Dana International": /* MyString takes care of remapping */
Note that this option supprts multiple keys and containers as well, e.g. FirstName, LastName (if only these were unique...)
Another option is if MyContainer is a singleton.
One more thing to consider is, how often does name change?