I was looking at the documentation page for jScroll plugin for jQuery (http://demos.flesler.com/jquery/scrollTo) and I noticed this :
$(...).scrollTo( $('ul').get(2).childNodes[20], 800 );
So, what does the three dots in jQuery mean ? I have never seen this selector before
EDIT :
DOM Element
This is from the source HTML. Viewing the source for the following links :
Relative
selectorjQuery
objectDOM
ElementAbsolute
numberAbsolute
all give the same implementation.
EDIT : I didnt look at the attribute clearly, its for the title attribute. I assumed its the href attribute. Feel silly asking this question now :) Thanks for the answers
I am fairly certain that he was using that as an example.
$( ... ) would be akin to $( your-selector-here ).
In other words, I have never seen any implementation of that.
Typically ... is used in various docs to shorten the example, and it means that you put something in place of the dots, or that what you would put there was omitted (to shorten the example)
It's not actually valid JS syntax.
It has no meaning. They meant just write your own selector.
Check out the souce code
$('div.pane').scrollTo( 0 );
They are not syntactically correct. They are just way the author uses to say scroll to some element, the name of which I don't bother to write here so I just write dots. Check the source code of the page if in doubt.
Three dots in javascript is Spread Syntax see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals)
Related
There's an element to which I'm giving a class success. But React-Mui appends a text to it on DoM, say, something like mui-AbcXYZ-success. So when I'm doing this
expect( getByTestId('thirdCheck')).toHaveClass("success")
I don't get this test passing as it expects the complete name mui-AbcXYZ-success. I’m getting this passed only when I provide the exact name (wirh hyphenated text and random number that mui adds)
How do I test that?
I tried doing the following without reasult:
expect( getByTestId('thirdCheck')).toHaveClass(/success/)
I also tried applying .className or .classList but that doesn’t give me the list of classes on the element.
After hours of frustrations, this is how I did and if any one has a better solution, feel free to post. I shall accept it.
let classes = getByTestId('thirdCheck').getAttribute('class'); //returns something like "Mui-root mui-AbcXYZ-success"
classes=classes.split(' ')[1].split('-'); //first split is to split on the basis of spaces and the second one to do on the bases of hyphen
expect(classes.includes('success'));
Looks like a bit verbose for a trivial-looing thing. But that's how did.
UPDATE:
#Fyodor has a great point in the comment.
We can simply do this as follows:
expect(getByTestId('thirdCheck').getAttribute('class')).toMatch(/success/gi)
With CSS-in-JS, classNames will sometimes get appended with generic identifiers. So it is nice to have a quick way of verifying your custom class is on an element. This is a loose one line approach for verifying the substring of a custom class without regex.
Note: It does not ignore casing. If you need that, then the answer with toMatch is a better solution for you.
expect(yourSelectedElement.getAttribute("class")).toContain("yourClassSubstring");
This is part of a simple script that will produce a warning popup. Currently, it works for any links with a ":" as seen below. I'd like to add a second variable, so it will work for EITHER a ":" OR "#tabs-2".
$(function(){
$('a[href*=":"]').click(ask) // all links that have a colon in them.
})
Thanks!
First of all, you're not seeking to add a 'variable'; there's no variables at play here. What you're seeking to do is to widen your jQuery selector (a string) to match more elements than it currently does.
This is achieved by specifying the variants separated by commas:
$('a[href*=":"], #tabs-2') //<-- note comma
Beware, though: #tabs-2 sounds, to me, like a container, so you might actually mean something like
$('a[href*=":"], #tabs-2 a')
Just use a comma and specify another selector:
$(function(){
$('a[href*=":"], #tabs-2').click(ask) // all links that have a colon in them.
})
Use it as:
$('a[href*=":"], #tabs-2').click(ask);
jQuery("input[name=a.b.c]")
Executing this line using jQuery 1.10.2 or 1.9.1 results in the message:
"Syntax error, unrecognized expression: input:hidden[name=a.b.c]".
I understand the core problem which is that the dots are not escaped or quoted out. This would work:
jQuery("input[name='a.b.c']")
The constraint is that I do not have the ability to change the line of code with the bad selector. That line is produced by the website (which I don't own) and they don't give me the ability to change that.
However, they do allow me to add arbitrary JS files to the header of the page (which means I can use a different jQuery version or even edit the jQuery file). My question is whether anyone knows another way around this so that jQuery can cope without the quotes since I cannot change the bad code.
For those saying that I can just change the name, this doesn't help because the JS still throws an error because changing the name of the element doesn't fix the bad selector.
Thanks
The proper way of executing this selector is:
jQuery('input[name="a.b.c"]')
Obviously you need to edit the algorithm that creates this line, there's no way jquery will accept an invalid selector.
Take a look here.
How do I extend jQuery's selector engine to warn me when a selector is not found?
In your case I would do something like this.
var oldInit = $.fn.init;
$.fn.init = function(selector, context, rootjQuery) {
selector = fixItWithQuotes(selector, context, rootjQuery);
return new oldInit(selector, context, rootjQuery);
};
untested by me, but it should give you an idea.
Also, this might give you more ideas?
http://blog.tallan.com/2012/01/17/customizing-the-default-jquery-selector-behavior/
Hope that makes sense.
Why don't you change the name attribute yourself?
var el = $("input");
el.attr("name", el.attr("name").replace(/[\d\.]+/g, ""));
console.log(el.attr("name"));
Then change it back if you need to. jsFiddle here
For example in javascript code running on the page we have something like:
var data = '<html>\n <body>\n I want this text ...\n </body>\n</html>';
I'd like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the DOM and selecting from there.
First, it's a string:
var arbitrary = '<html><body>\nSomething<p>This</p>...</body></html>';
Now jQuery turns it into an unattached DOM fragment, applying its internal .clean() method to strip away things like the extra <html>, <body>, etc.
var $frag = $( arbitrary );
You can manipulate this with jQuery functions, even if it's still a fragment:
alert( $frag.filter('p').get() ); // says "<p>This</p>"
Or of course just get the text content as in your question:
alert( $frag.text() ); // includes "This" in my contrived example
// along with line breaks and other text, etc
You can also later attach the fragment to the DOM:
$('div#something_real').append( $frag );
Where possible, it's often a good strategy to do complicated manipulation on fragments while they're unattached, and then slip them into the "real" page when you're done.
The correct answer to this question, in this exact phrasing, is NO.
If you write something like var a = $("<div>test</div>"), jQuery will add that div to the DOM, and then construct a jQuery object around it.
If you want to do without bothering the DOM, you will have to parse it yourself. Regular expressions are your friend.
It would be easiest, I think, to put that into the DOM and get it from there, then remove it from the DOM again.
Jquery itself is full of tricks like this. It's adding all sorts off stuff into the DOM all the time, including when you build something using $('<p>some html</p>'). So if you went down that road you'd still effectively be placing stuff into the DOM then removing it again, temporarily, except that it'd be Jquery doing it.
John Resig (jQuery author) created a pure JS HTML parser that you might find useful. An example from that page:
var dom = HTMLtoDOM("<p>Data: <input disabled>");
dom.getElementsByTagName("body").length == 1
dom.getElementsByTagName("p").length == 1
Buuuut... This question contains a constraint that I think you need to be more critical of. Rather than working around a hard-coded HTML string in a JS variable, can you not reconsider why it's that way in the first place? WHAT is that hard-coded string used for?
If it's just sitting there in the script, re-write it as a proper object.
If it's the response from an AJAX call, there is a perfectly good jQuery AJAX API already there. (Added: although jQuery just returns it as a string without any ability to parse it, so I guess you're back to square one there.)
Before throwing it in the DOM that is just a plain string.
You can sure use REGEX.
I have the following being extracted from an XML and being put into a jQuery variable.
links.append($("<a href='"+alink+"'></a> ").html(desc));
...however the does not output onto the page. I need this to separate the hrefs on output
I have also tried
links.append($("<a href='"+alink+"'></a>").html(desc));
links.append($(" "));
Many thanks!
$("<a href='"+alink+"'></a> ")
Yeah, that's actually only creating the <a> element, and discarding the nbsp. When you pass a string into the $() function that looks like(*) HTML, jQuery creates the stretch of markup between the first < in the string and the last >. If you've got any leading or trailing content outside those, it gets thrown away(**). You could fool jQuery by saying:
$("<a href='"+alink+"'></a> <!-- don't ignore me! -->")
This doesn't seem to be documented anywhere, makes no sense whatsoever, and might be considered a bug, but it has been jQuery's normal behaviour for some time so it's probably not going away.
When you pass an HTML string to the append function (and other manipulation methods) directly instead of via the $ function, this behaviour does not occur. So:
links.append("<a href='"+alink+"'></a> ");
actually does keep the space. But a better way forward is to stop throwing HTML strings about, so you don't have to worry about alink containing ', < or & characters either, and work in a more DOM style:
var link= $('<a/>');
link.attr('href', alink);
link.html(desc);
links.append(link);
links.append('\xA0');
Or, more concisely, using jQuery 1.4's props argument shortcut:
links.append($('<a/>', {href: alink, html: desc}));
links.append('\xA0');
assuming that desc is really something that should contain HTML markup; if not, use text instead.
(I used \xA0, the JavaScript string literal way to include a character U+00A0 NON-BREAKING SPACE as it is a whole two characters shorter than the HTML entity reference. Woohoo!)
(*: how does it tell that a string is HTML? Why, by checking to see if there's a < and > character in it, in that order, of course. Meaning it'll get fooled if you try to use a selector that has those characters in. Brilliant, jQuery, brilliant.(***))
(**: why? see line 125 of jQuery 1.4.2. It builds the HTML fragment from match[1]—the group from the first < to the last > in quickExpr—and not the original string or match[0].)
(***: I'm being sarcastic. The insane over-overloading of the $ function is one of jQuery's worst features.)
You better style with css, something like :
links.append($("<a class='link' href='"+alink+"'></a>").html(desc));
in css :
a.link {
padding-left : 5px ;
padding-right : 5px ;
}
you could try