jquery get elements by class name - html

I'm using Jquery to get a list of elements having a class "x".
html:
<p class="x">Some content</p>
<p class="x">Some content#2</p>
If we use Jquery to get both these html elements and do something with it- we use something like:
$(".x").text("changed text");
This will change the text of both the paragraphs. From $(".x") - How can we add a array - subscript notation like we can do with getElementsByclassName as follows:
document.getElementsByClassName("x")[0].innerHTML
I tried this
$(".x")[0].text("asasa")- it doesn't work gives a typeerror in javascript console. I also tried get API here -http://jsfiddle.net/probosckie/jnz825mp/ - and it doesnt work
the error is Uncaught TypeError: $(...).get(...).text is not a function
None of the solutions below WORK!

You can use the get() method for accessing an element from the array, for example:
$(".x").get(index).textContent = "changed text";
More info: https://api.jquery.com/jquery.get/
And for obtaining HTML (innerHTML) you call the .html() function:
// This is equal to document.getElementsByClassName("x")[0].innerHTML
$(".x").get(0).innerHTML;
If you want to set the HTML, then just provide your HTML code inside the function call like this .html('<h1>Hello, World!</h1>').
EDIT: .get() returns the DOM object not the jQuery wrapped element. Therefore .text() and .html() doesn't work. Unless you wrap it.
More options:
$(".x").get(0).innerHTML;
$($(".x").get(0)).html();
$(".x:first").html();

You can do it like this way:
$('.x:eq(0)').text('changed text');
or:
$('.x').eq(1).text('bbb');
both works well
sorry for my before answer..

The solution $(".x").get(index)... will first match all .x (which is bad performance). And then it will filter
If you have 1000 .x it will fill an 1000 items in the jQuery object (before filtered)
But
$(".x:first").text("changed text"); will do better because it won't yield all .x and then filter , but will do it at a first single step (without filling 1000 items)

Related

How to pass html element into rowDragText callback

I am not even sure if what I am trying to do is possible. I want to present the "floating" DOM element created when dragging a row as something more than just text. Seems like when I try to use html code as the returned value it is rendered as text rather than html:
rowDragText: function(params) {
return `<div [innerHTML]=${params.rowNode.data.RULE_NAME}></div>`;
}
This is what happens:
There is public static GHOST_TEMPLATE defined in dragAndDropService.ts.
You can try modifiying that template and perhaps also inspect the createGhost function nearby.
rowDragText probably not used with this method...

Parent node in react-testing-library

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('...');

Display JSON object nicely with Syntax Hihjlighter

I'm trying to display a JSON object nicely (this means on several lines with indentation) with Alex Gorbatchev plugin : http://alexgorbatchev.com/SyntaxHighlighter/
Unfortunately, it all displays on a single line.
I'm using the javascript brush.
I've created a code pen : http://codepen.io/hugsbrugs/pen/XJVjjP?editors=101
var json_object = {"hello":{"my_friend":"gérard", "my_dog":"billy"}};
$('#nice-json').html('<pre class="brush: javascript">' + JSON.stringify(json_object) + '</pre>');
SyntaxHighlighter.highlight();
Please don't give a list of other plugins since I know there is a bunch but I don't want to load additional plugins ... I'd like to achieve it with this plugin.
Thanks for your help
Try indenting the json with the stringify method.
JSON.stringify(json_object, undefined, 2);
You can use the optional third parameter of JSON.stringify(...) which is the space argument.
Change:
JSON.stringify(json_object)
to:
JSON.stringify(json_object, null, '\t')
Here is your codepen updated to show the result of the above modifications. The above modification causes your JSON to be pretty printed over multiple lines.

Binding to events on parent page from iframe [duplicate]

I have an iframe and in order to access parent element I implemented following code:
window.parent.document.getElementById('parentPrice').innerHTML
How to get the same result using jquery?
UPDATE: Or how to access iFrame parent page using jquery?
To find in the parent of the iFrame use:
$('#parentPrice', window.parent.document).html();
The second parameter for the $() wrapper is the context in which to search. This defaults to document.
how to access iFrame parent page using jquery
window.parent.document.
jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $.
If you need to find the jQuery instance in the parent document (e.g., to call an utility function provided by a plug-in) use one of these syntaxes:
window.parent.$
window.parent.jQuery
Example:
window.parent.$.modal.close();
jQuery gets attached to the window object and that's what window.parent is.
You can access elements of parent window from within an iframe by using window.parent like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
in parent window put :
<script>
function ifDoneChildFrame(val)
{
$('#parentPrice').html(val);
}
</script>
and in iframe src file put :
<script>window.parent.ifDoneChildFrame('Your value here');</script>
yeah it works for me as well.
Note : we need to use window.parent.document
$("button", window.parent.document).click(function()
{
alert("Functionality defined by def");
});
It's working for me with little twist.
In my case I have to populate value from POPUP JS to PARENT WINDOW form.
So I have used $('#ee_id',window.opener.document).val(eeID);
Excellent!!!
Might be a little late to the game here, but I just discovered this fantastic jQuery plugin https://github.com/mkdynamic/jquery-popupwindow. It basically uses an onUnload callback event, so it basically listens out for the closing of the child window, and will perform any necessary stuff at that point. SO there's really no need to write any JS in the child window to pass back to the parent.
There are multiple ways to do these.
I) Get main parent directly.
for exa. i want to replace my child page to iframe then
var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);
here top.location gets parent directly.
II) get parent one by one,
var element = $('.iframe:visible', window.parent.document);
here if you have more then one iframe, then specify active or visible one.
you also can do like these for getting further parents,
var masterParent = element.parent().parent().parent()
III) get parent by Identifier.
var myWindow = window.top.$("#Identifier")

Any difference between .innerHTML and .set('html','') in mootools?

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.