transforming tree to sequence of elements - xquery

I have something like this
<a>
<b>
<c>1</c>
<d>2<e>3</e></d>
</b>
</a>
and I want to obtain a sequence like this
<a/>
<b/>
<c>1</c>
<d>2<e>3</e></d>
that is, when recursing, every time an element occurs which does not have a text node, I want to output the element as an empty element, whereas every time an element with a text node occurs, I want to output it as it is. Of course, the text nodes in the above input have to be space-normalized.
If I put it through a standard identity transform,
declare function local:copy($element as element()) as element() {
element {node-name($element)}
{$element/#*,
for $child in $element/*
return
if ($child/text())
then $child
else (element {node-name($child)}{$child/#*}, local:copy($child))
}
};
<b> gets reconstructed as a full element (containing <c> and <d>), but if I remove the element constructor, it does not get output at all.

I don't quite get the fourth line in your example output, I'm just guessing what you want is actually this:
<a/>
<b/>
<c>1</c>
<d>2</d>
<e>3</e>
You don't need any functions. Just list all elements, reconstruct one with same name and include it's text node children.
for $element in //*
return element { local-name($element) } { $element/text() }
This version is even shorter, but I think it requires XQuery 3.0, because earlier versions did not allow element constructors in step expressions:
//*/element { local-name(.) } { text() }

Related

Testing contents of after CSS selector in protractor

In my HTML I have element such as below
HTML:
<hmtl>
<head>
<style>
label::after {
content: " *"
}
</style>
</head>
<body>
<label> I'm mandatory</label>
</body>
</hmtl>
So what gets displayed on browser is:
I'm mandatory *
Query Selector
>getComputedStyle(document.querySelector('label')).content
<"normal"
So I see normal instead of *.
I can't see where is normal coming from. Is this the correct way to test content of ::after CSS selector?
I want to test that there's a "*" after the label, but can't seem to be able to get the value of "content" property correctly. Once I'm able to find it in using browser DOM API, I'd eventually want to test it in protractor.
Update
I found the answer at - Selenium WebDriver get text from CSS property "content" on a ::before pseudo element.
Now the question remains how I would test this on protractor.
Window.getComputedStyle()
The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.
Syntax:
var style = window.getComputedStyle(element [, pseudoElt]);
element
The Element for which to get the computed style.
pseudoElt (Optional)
A string specifying the pseudo-element to match. Omitted (or null) for real elements.
The returned style is a live CSSStyleDeclaration object, which updates automatically when the element's styles are changed.
You can find a related discussion in WebDriver select element that has ::before
Usage with pseudo-elements
getComputedStyle() can pull style info from pseudo-elements (such as ::after, ::before, ::marker, ::line-marker.
As per the HTML, the <style> is as follows:
<style>
label::after {
content: " *"
}
</style>
Implemented as:
<label> I'm mandatory</label>
To retrieve you need to:
var label = document.querySelector('label');
var result = getComputedStyle(label, ':after').content;
console.log('the generated content is: ', result); // returns ' *'
Reference
CSS Pseudo-Elements Module Level 4
const label = document.querySelector('label'); // "normal";
console.log(label);
const labelAfter = getComputedStyle(label, ':after').content;
console.log(labelAfter == "normal");
label::after {
content: " *"
}
<label> I'm mandatory</label>
Since my question was specifically w.r.t protractor I'm posting the solution that I got working. Coming to the part I was stuck initially - why do I get "normal" instead of " *"
>getComputedStyle(document.querySelector('label')).content
<"normal"
So earlier I was unaware that ::after creates a pseudo child element inside the label element.
Inspecting <label> element in Chrome shows the below HTML
<label>
I'm mandatory
::after
</label>
If I click<label> element and checked the Computed tab, I could see that the value for content property is normal.
However, if I click on ::after pseudo-element, I can see in the Computed tab the value for content property is " *".
As mentioned in the other answers getComputedStyle() with the pseudo element as second parameter, is the only way to get value of CSS property for "::after". The crux of the problem is that protractor does not have an equivalent for getComputedStyle(), so we have to rely upon browser.executeScript() as shown below:
let labelHeader = 'I'm mandatory *';
// Passing label element separately as in the real test case, it would be extracted from parent
// enclosing element and need to be able to pass it as a parameter to browser.executeScript().
let label = element(by.css('label'));
browser.executeScript("return window.getComputedStyle(arguments[0], ':after').content",
label)
.then ((suffixData: string) => {
// suffixData comes out to be '" *"', double quotes as part of the string.
// So get rid of the first and last double quote character
suffixData = suffixData.slice(1, suffixData.length - 1);
labelText += suffixData;
expect(labelText).toBe(labelHeader);
});

:empty doesn't work if there's blank spaces?

Trying to find a pseudo class that'll target a <div> like this:
<div class="nav-previous">
</div>
I've tried :blank and :empty but neither can detect it. Is it just not possible to do?
https://jsfiddle.net/q3o1y74k/3/
:empty alone is enough.
By the current Selectors Level 4 specification, :empty can match elements that only contain text nodes that only contain whitespace as well as completely empty ones. It’s just there aren’t many that support it as per the current specification.
The :empty pseudo-class represents an element that has no children except, optionally, document white space characters.
From the MDN:
Note: In Selectors Level 4, the :empty pseudo-class was changed to act like :-moz-only-whitespace, but no browser currently supports this yet.
The :-moz-only-whitespace CSS pseudo-class matches elements that only contain text nodes that only contain whitespace. (This includes elements with empty text nodes and elements with no child nodes.)
As the others mentioned, this isn't possible with CSS yet.
You can check to see if there's only whitespace with JavaScript however. Here's a simple JS only solution, "empty" divs that match are blue, while divs that have text are red. Updated to add an empty class to the empty divs, which would allow you to target them easily with the selector .empty in your CSS.
The JS only "empty" comparison would look like this:
if(element.innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") == "")
And if you're using jQuery it would be a bit easier:
if( $.trim( $(element).text() ) == "" ){
var navs = document.querySelectorAll(".nav-previous");
for( i=0; i < navs.length; i++ ){
if(navs[i].innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") == "") {
navs[i].style.background = 'blue';
navs[i].classList.add( 'empty' );
} else {
navs[i].style.background = 'red';
}
}
.nav-previous {
padding: 10px;
border: 1px solid #000;
}
.nav-previous.empty {
border: 5px solid green;
}
<div class="nav-previous">
</div>
<div class="nav-previous">Not Empty </div>
The problem with your approach is that your container is not actually empty.
The :empty pseudo-class represents an element that has no children at
all. In terms of the document tree, only element nodes and content
nodes (such as DOM text nodes, CDATA nodes, and entity references)
whose data has a non-zero length must be considered as affecting
emptiness;
As you have empty spaces this pseudo class will not do the trick.
The :blank pseudo class should be the right one, because this is its definition:
This blank pseudo-class matches elements that only contain content
which consists of whitespace but are not empty.
the problem is that this pseudo class isn't implemented by any browser yet as you can check in the link below. So you will need to wait until it get implemented to be able to use this selector.
This pretty much explains the behavior you are facing
https://css4-selectors.com/selector/css4/blank-pseudo-class/
The best approach here is just to be sure that your div will actually be empty, so your approach will work.
the best that you can do is to define an empty class like this:
.empty{
display:none;
}
and then add this JS code here, it will append the empty class to your blank items:
(function($){
$.isBlank = function(html, obj){
return $.trim(html) === "" || obj.length == 0;
};
$('div').each(function() {
if($.isBlank(
$(this).html(),
$(this).contents().filter(function() {
return (this.nodeType !== Node.COMMENT_NODE);
})
)) {
$(this).addClass('empty');
}
});
})(jQuery);
check it working here,
https://jsfiddle.net/29eup5uw/
You just can't without JavaScript/jQuery implementation.
:empty selector works with empty tags (so without even any space in them) or with self-closing tags like <input />.
Reference: https://www.w3schools.com/cssref/css_selectors.asp
If you want to use JavaScript implementation, I guess here you will find the answer: How do I check if an HTML element is empty using jQuery?
:empty indeed only works for totally empty elements. Whitespace content means it is not empty, a single space or linebreak is already enough. Only HTML comments are considered to be 'no content'.
For more info see here: https://css-tricks.com/almanac/selectors/e/empty/
The :blank selector is in the works, it will match whitespace, see here: https://css-tricks.com/almanac/selectors/b/blank/. But it seems to have no browser support yet.
Update:
See here for possible solutions to this involving jQuery.

Css selector for getting web element based on text

Below is the dom structure of the page :
I have tried
button:contains("srave")
I also tried
button[innerText="srave"]
button[text="srave"]`
button[innerHtml="srave"]`
none of them work.
Need way to get elements when element attribute is not defined.
PS: textContent() return srave as outcome.
Edit:
I have many such button elements on the page. I know I can iterate through all of them and check text. But I want to get web element directly based on the text it contains to reduce the execution time
Did you try: button[class='k-button k-button-icontext'] or button[dir='ltr'] I don't think the cssSelectors you were attempting in your example are correct because you pluralized button. If neither of these work, it may be that there are more than one button on the page with the same selector. In which case it might be better to use xpath or you could get a list of all the elements with the same selector and then get whichever one from that list you created and click it.
No, you can't use CSS Selector. You can use XPath.
//button[text()='srave']
Or
//button[contains(text(),'srave')]
You can use jquery for get the same because css is not select the text.
Working fiddle
fiddle link
Try this
alert($('button').find('span').html());
You can use following css to get the button name with "srave".
HTML
<button data-name="srave">
<span>Brave</span>
</button>
css
button[data-name="srave"] {
background:tomato;
}
To add to danidangerbear here is a java method that will do what you want:
public String getElementText(String elementText){
List<WebElement> elements = driver.findElements(By.cssSelector("button"));
String elementText = null;
for(WebElement element : elements)
if(element.getText().equals(actualValue)){
elementText = element.getText();
break;
} else {
elementText = "element text does not exist";
continue;
}
return elementText;
}

How to select part of a custom element with CSS?

To select all elements that start with the class name foo. I can use:
[class^="foo"] { }
What can I use to select a custom element that starts with foo.
Example:
<foo-bar>Hola</foo-bar>
<foo-bazz>Hola</foo-bazz>
I want to have a single selector for both elements.
You can't. The [...] selectors only work on attributes, not element types themselves.
What you can do though, as I'm sure you're already aware, is chain them all into one selectors group, but this will mean that you'll need to know the exact element names:
foo-bar,
foo-bazz {
...
}
Failing that, you can always just give them all a shared class or data-* attribute:
<foo-bar class="foo"></foo-bar>
<foo-bazz class="foo"></foo-bazz>
.foo {
...
}

CSS selector (id contains part of text)

I have a question.
I have elements something like this:
<a> element with id = someGenerated Some:Same:0:name
<a> element with id = someGenerated Some:Same:0:surname
<a> element with id = someGenerated Some:Same:1:name
<a> element with id = someGenerated Some:Same:1:surname
I need CSS selector to get names. The problem is that I don't know how to get it.
I tried a[id*='Some:Same'] - it returned all <a> elements. After I can get elements which id ends with name. But I don't like this idea. I think that it can be done with some other selector.
Try this:
a[id*='Some:Same'][id$='name']
This will get you all a elements with id containing
Some:Same
and have the id ending in
name
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="123_wrapper"] {
}
The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

Resources