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");
Related
I'm tring to capture the hexadecimal colour code of the background-color of an element with javascript. I use this script:
style = select.find(":selected").attr("style");
match = style.match(/background-color ?: ?(#[0-9a-f]{6})/i);
console.log(match);
The code above results in match array has two elements:
0: "background-color:#f"
1: "#f"
And I can't figure out why does my regex capture only '#' and the first actual character of the 6 char long hexadec code. I have tried to add the 'global' modifier but still the same result. How should my regex look like?
Here is a example about what I want:
From any kind of inline css definition something like:
"border:1px solid #00ffff; background-color: #00ffaa; width: 500px ...etc" match the "background-color: #00ffaa" part and extract the "#00ffaa" part.
Try this regex:
var string = "border:1px solid #00ffff; background-color: #00ffaa; width: 500px ...etc";
var answer = string.match(/background-color\s*:\s*([^;]+)/);
console.log(answer);
document.write(answer[0] + '<br>' + answer[1]);
Hope it helps.
There are likely to be better ways to accomplish what you are trying to--which is what?
I presume that you want to find the color of some element because it means something--such as, if the background is blue, it's the sidebar, or if the button's background is gray, it's disabled, or in your case, if the selected option is pink, then it's a dog. In essence, you're storing part of the state of your application in CSS properties. But as you've found, once you've set the CSS it may not be trivial to get it back out again. So the most basic solution is to see if there's a way to manage the state of the application in JS.
In your case, you seem to be wanting to get the background color of the selected option in a select element, in order to do something with it. Consider instead maintaining an array of relevant information for each option; or putting a data attribute on each option that you get easily; or some other approach that does not require rummaging around down inside the style string.
Second, experienced HTML/CSS folks pretty much agree that using individual style properties is less preferable than using classes. With classes, I can set a bundle of properties on an element just by setting the class; and I can easily query, remove, or replace classes with standard DOM or jQuery APIs.
Third, it is also pretty much agreed that using regexp to parse languages--even one as simple as CSS--it not a good idea. You'll always miss something, and then your regexp will break. For instance, in your original regexp, and the one in one of the answers, the regexp will not work unless there is exactly zero or one space around the colon. Some poor soul--perhaps you, perhaps some new guy coming in six months from now--is going to have to track down and fix the bug that will arise when someone puts two spaces after the colon.
Or you will assume that the background color is always set using a hex value--and build your code on that assumption. But then the new guy comes along and decides to specify a color using hsl--and again the code will break.
Fourth, if it is an issue for you, the "regexp on style string" approach will work only when the background color property is set explicitly on that element. If background color comes from a CSS rule, for example, this approach will not pick it up. Normally, this is the point at which people suggest using getComputedStyle or jQuery's .css(), which will indeed work (although you'll still get back the rgb(r,g,b) format, which if you really want to have in hex format you'll have to convert)--but the question remains, why are you "storing" information in the CSS that you need to get back out again? There are certainly use cases for this, but they are relatively rare.
If you are sure you need to retrieve the background color, from the style on the particular element, and in hex format (why?), then get it and convert it:
backgroundColor = select.find(":selected").css('backgroundColor');
rgbColor = convertRGBToHex(style);
You can find plenty of approaches to convertRGBToHex here on SO or elsewhere.
try the following
var txt='border:1px solid #00ffff; background-color: #00ffaa;';
var match = txt.match(/background-color ?: ?(#{1}(?:[A-F0-9]){6})(?![0-9A-F])/i);
console.log(match);
document.write(match[1])
If I have markup like this:
<div id="foo"></div>
and I want to detect later whether div#foo still contains that same character entity, I'd like to be able to do so by comparing it to rather than to (which in my code base is rather obtuse for maintenance purposes).
I've tried things like this (using jQuery):
console.log($('<textarea />').html($('#foo').html()).val());
But that seems to still output the nice little square "what you talkin' 'bout" character rather than the desired .
I'm open to plain JavaScript or jQuery-specific solutions.
You can use a Unicode entity in JavaScript. For example:
(HTML: <div id='foo'></div>)
JavaScript:
console.log($('#foo').html().charCodeAt(0).toString(16));
//=> f067
console.log($('#foo').html().indexOf('\uf067'));
//=> 0
Here's a JSFiddle.
I'm sorry,I can't believe this question is not solved in stackoverflow but I've been searching a lot and I don't find any solution.
I want to change HTML code with regular expressions in this way:
testing anchor
to
testing anchor
Only I want to unlink a text code without use DOM functions, the code is in a string not in the document and I don't want to remove other tags that the a ones.
If you really don't want to use DOM functions (why ?) you might do
str = str.replace(/<[^>]*>/g, '')
You can use it if you're fairly confident you don't have a more complex HTML but it will fail in many cases, for example some nested tags, or > in an attribute. You might fix some of the problems with more complex regular expressions but they aren't the right tool for this job in the general case.
If you don't want to remove other tags than a, do this :
str = str.replace(/<\/?a( [^>]*)?>/g, '')
This changes
<a>testing</a> <b>a</b>nchor<div>test</div><aaa>E</aaa>
to
testing <b>a</b>nchor<div>test</div><aaa>E</aaa>
I know you only want regex, for future viewers, here is a trivial solution using DOM methods.
var a = document.createElement("div");
a.innerHTML = 'testing anchor';
var wordsOnly = a.textContent || a.innerText;
This will not fail on complicated use cases, allows nested tags and it's perfectly clear what's happening:
Hey browser! Create an element
Put that HTML in it
Give me back just the text, that's what I want now.
NOTE:
The element we're creating will not be added to the actual DOM since we're not adding it anywhere, it'll stay invisible. Here is a fiddle to illustrate how this works.
As has been mentioned, you cannot parse HTML with regular expressions. The principal reason is that HTML elements nest and regular expressions cannot handle that.
That said, with a few restrictions which I will mention, you can do the following :
string.replace (/(\b\w+\s*)<a\s+href="([^"]*)">(.*)<\/a>/g, '$1 $3')
This requires there to be a word before the tag, spacing between the word and the tag is optional, no attributes other than the href specified in the <a> tag and you accept anything between the <a> and the .
You can create a DOM object from the string, use DOM methods to parse, without having had appended said DOM object to the document
I am trying to get the innerHTML of a hidden span. The JavaScript is from an iframe HTML page, and the hidden span resides in the parent page. A different function works when accessing contents of a list from the parent, but I can't seem to get at my span...
WORKS
document.getElementById(parent.genL[i]);
DOESNT WORK
document.getElementById(parent."span"+i).innerHTML;
- SyntaxError: missing name after . operator
The above line of code resides in a for loop and as it iterates through i it will grab data from each separate span. the hidden spans start at ID "span1" through upwards of 10-40k different hidden spans.
Anyways, I have a feeling that it has to do something with trying to concatenate the string int i. I assume i is an int anyways. Any thoughts? Thanks so much everyone!
Edit - Words, and added the innerHTML portion to the doesn't work line of code. Not sure if that will be making a difference or not...
Edit2 - Great answers everyone, learned some good syntactical tricks :) I simply moved the parent. portion to the front of the code as reccomend by the comment of mplungjan and the answer from Jacob T. Nielson. For some reason I still got the error using the brackets as suggested, but I will definitely tuck the brackets into my memory for future similar situations!
parent.document.getElementById("span"+i).innerHTML;
:)
Try changing it to an indexer.
document.getElementById(parent["span"+i]);
If the parent in the brackets is an object and you're trying to access something like parent.span1 then you need to use bracket notation instead of the dot.
document.getElementById(parent["span"+i]); should work fine.
I think what you are trying to do is get the i-th span element on the parent page. Correct?
You can do it like this
var s = parent.document.getElementsByTagName('span')[i];
s.innerHTML // <-- access innerHTML
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)