DOM Selector to get text of element ignoring children? - html

I'm using the Tab Modifier plugin for Chrome to dynamically rename some tabs that I use daily. In the tab Title definition, it says the following:
You can inject any DOM content with {selector}. Examples: {title} for website title, {h1}, {#id}, {.class}, etc.
Here is an example of the element I want to use to name the tab:
<td class="portalTitleInfoVal">
PORTALNAME
<a class="portalLink">Change Portal</a>
</td>
This is what I'm currently using for the title:
{.portalTitleInfoVal:nth-of-type(4)}
But, of course, the tab is named PORTALNAMEChange Portal.
How can I modify the DOM selector so that the tab is just named "PORTALNAME"?

I know I'm really late to the party, but I found this post while searching for an answer.
I'm working with a lot of old systems and all the tabs just says {title}, which is.. not useful when having 15-20 tabs open at once, and it's tedious to hard code every tab.
So.. I brute forced tested until I found a solution:
Every page has a breadcrumb:
<div class="breadcrumb noPrint">
Home "ยป"
Materials
123123
</div>
So they might have updated the extension since, but your guess was very close. I don't know why you were putting in 4, but I assume you had more elements than posted.
Anyhow, the way I got it to work were by:
{.breadcrumb :nth-last-child(2)} : {.breadcrumb :last-child}
So, there has to be a space between the .class and the child element, which in my case returns Materials : 12312
I haven't tried nearly half, but DoFactorys list of CSS selectors were a big help for me.

The element's first child node is the plain text, before the HTML element (<a>).
$('. portalTitleInfoVal')[0].childNodes[0].nodeValue
It looks like this plugin will only allow for CSS style element selectors compatible with querySelector. It then grabs the text from that element. From their github repo:
/**
* Returns the text related to the given CSS selector
* #param selector
* #returns {string}
*/
getTextBySelector = function (selector) {
var el = document.querySelector(selector), value = '';
if (el !== null) {
value = el.innerText || el.textContent;
}
return value.trim();
};

Related

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

how to select an element from 'data-formatted' tag using selenium wedriver

I have a series of elements as:
<li data-formatted="12:00am" data-minutes="0">12:00am</li>
<li data-formatted="1:00am" data-minutes="10">1:00am</li>
<li data-formatted="2:00am" data-minutes="20">2:00am</li>
.
.
<li data-formatted="12:00pm" data-minutes="80">12:00pm</li>
The issue I face is of finding any one of the element from this list of li. I can use driver.findElements() only when I am atleast able to identify it using any property tag since it does not have any like name, css or id.
Any suggestions on how to find an element using data-formatted tag would be of great help. Thanks.
You can use CssSelector or XPath to find them.
Here are example expressions to find li element which has attribute data-formatted and the attribute contains "m":
driver.findElements(By.cssSelector("li[data-formatted*='m']"));
driver.findElements(By.xpath("//li[contains(#data-formatted, 'm')]"));
You can select elements with data attributes through querySelectorAll() API and access all element's data attributes directly with vanilla JS standard dataset API.
In your case, to get the elements with data-formatted attribute you may do like
var formettedEls = document.querySelectorAll("[data-formatted]");
or
var El1AM = document.querySelectorAll("[data-formatted = '1:00am']");
or as another option you can search among the formattedEls for your specific one through the dataset API like
function findData(set, searchDataProp, searchData){
Array.prototype.forEach.call(set, function(el){
(el.dataset[searchDataProp] == searchData) && console.log(el.dataset[searchDataProp], searchData);
});
}
findData(formattedEls, "formatted", "12:00am");

cloneNode issue with HTML5 nodes in IE

I am trying to clone an HTML node using cloneNode() method of browser's DOM API and even using Jquery clone() function. The API works perfectly fine with HTML tags, However i am facing some issues while using it with HTML5 tags like time e.g.
The issue is that following <time> tag content <time class="storydate">April 7, 2010</time> gets converted to: <:time class=storydate awpUniq="912">April 7, 2010. Although IE renders the original time node correctly then why such issue with the clone API.
And this issue isn't observed in FF/ chrome. Please give some clue how to avoid this
Is this of any help? From the HTML5 Shiv issue list:
http://code.google.com/p/html5shiv/issues/detail?id=28
Links to
http://pastie.org/935834#49
solution seems to be:
// Issue: <HTML5_elements> become <:HTML5_elements> when element is cloneNode'd
// Solution: use an alternate cloneNode function, the default is broken and should not be used in IE anyway (for example: it should not clone events)
// Example of HTML5-safe element cloning
function html5_cloneNode(element) {
var div = html5_createElement('div'); // create a HTML5-safe element
div.innerHTML = element.outerHTML; // set HTML5-safe element's innerHTML as input element's outerHTML
return div.firstChild; // return HTML5-safe element's first child, which is an outerHTML clone of the input element
} // critique: function could be written more cross-browser friendly?

shrink html help

I have an array of 2000 items, that I need to display in html - each of the items is placed into a div. Now each of the items can have 6 links to click on for further action. Here is how a single item currently looks:
<div class='b'>
<div class='r'>
<span id='l1' onclick='doSomething(itemId, linkId);'>1</span>
<span id='l2' onclick='doSomething(itemId, linkId);'>2</span>
<span id='l3' onclick='doSomething(itemId, linkId);'>3</span>
<span id='l4' onclick='doSomething(itemId, linkId);'>4</span>
<span id='l5' onclick='doSomething(itemId, linkId);'>5</span>
<span id='l6' onclick='doSomething(itemId, linkId);'>6</span>
</div>
<div class='c'>
some item text
</div>
</div>
Now the problem is with the performance. I am using innerHTML to set the items into a master div on the page. The more html my "single item" contains the longer the DOM takes to add it. I am now trying to reduce the HTML to make it small as possible. Is there a way to render the span's differently without me having to use a single span for each of them? Maybe using jQuery?
First thing you should be doing is attaching the onclick event to the DIV via jQuery or some other framework and let it bubble down so that you can use doSomething to cover all cases and depending on which element you clicked on, you could extract the item ID and link ID. Also do the spans really need IDs? I don't know based on your sample code. Also, maybe instead of loading the link and item IDs on page load, get them via AJAX on a as you need them basis.
My two cents while eating salad for lunch,
nickyt
Update off the top of my head for vikasde . Syntax of this might not be entirely correct. I'm on lunch break.
$(".b").bind( // the class of your div, use an ID , e.g. #someID if you have more than one element with class b
"click",
function(e) { // e is the event object
// do something with $(e.target), like check if it's one of your links and then do something with it.
}
);
If you set the InnerHtml property of a node, the DOM has to interpret your HTML text and convert it into nodes. Essentially, you're running a language interpreter here. More text, more processing time. I suspect (but am not sure) that it would be faster to create actual DOM element nodes, with all requisite nesting of contents, and hook those to the containing node. Your "InnerHTML" solution is doing the same thing under the covers but also the additional work of making sense of your text.
I also second the suggestion of someone else who said it might be more economical to build all this content on the server rather than in the client via JS.
Finally, I think you can eliminate much of the content of your spans. You don't need an ID, you don't need arguments in your onclick(). Call a JS function which will figure out which node it's called from, go up one node to find the containing div and perhaps loop down the contained nodes and/or look at the text to figure out which item within a div it should be responding to. You can make the onclick handler do a whole lot of work - this work only gets done once, at mouse click time, and will not be multiplied by 2000x something. It will not take a perceptible amount of user time.
John Resig wrote a blog on documentDragments http://ejohn.org/blog/dom-documentfragments/
My suggestion is to create a documentDragment for each row and append that to the DOM as you create it. A timeout wrapping each appendChild may help if there is any hanging from the browser
function addRow(row) {
var fragment = document.createDocumentFragment();
var div = document.createElement('div');
div.addAttribute('class', 'b');
fragment.appendChild(div);
div.innerHtml = "<div>what ever you want in each row</div>";
// setting a timeout of zero will allow the browser to intersperse the action of attaching to the dom with other things so that the delay isn't so noticable
window.setTimeout(function() {
document.body.appendChild(div);
}, 0);
};
hope that helps
One other problem is that there's too much stuff on the page for your browser to handle gracefully. I'm not sure if the page's design permits this, but how about putting those 2000 lines into a DIV with a fixed size and overflow: auto so the user gets a scrollable window in the page?
It's not what I'd prefer as a user, but if it fixes the cursor weirdness it might be an acceptable workaround.
Yet Another Solution
...to the "too much stuff on the page" problem:
(please let me know when you get sick and tired of these suggestions!)
If you have the option of using an embedded object, say a Java Applet (my personal preference but most people won't touch it) or JavaFX or Flash or Silverlight or...
then you could display all that funky data in that technology, embedded into your browser page. The contents of the page wouldn't be any of the browser's business and hence it wouldn't choke up on you.
Apart from the load time for Java or whatever, this could be transparent and invisible to the user, i.e. it's (almost) possible to do this so the text appears to be displayed on the page just as if it were directly in the HTML.

Which HTML elements can receive focus?

I'm looking for a definitive list of HTML elements which are allowed to take focus, i.e. which elements will be put into focus when focus() is called on them?
I'm writing a jQuery extension which works on elements that can be brought into focus. I hope the answer to this question will allow me to be specific about the elements I target.
There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are
HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.
Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:
HTMLAnchorElement/HTMLAreaElement with an href
HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
Any element with a tabindex
There are likely to be other subtle exceptions and additions to this behaviour depending on browser.
Here I have a CSS-selector based on bobince's answer to select any focusable HTML element:
a[href]:not([tabindex='-1']),
area[href]:not([tabindex='-1']),
input:not([disabled]):not([tabindex='-1']),
select:not([disabled]):not([tabindex='-1']),
textarea:not([disabled]):not([tabindex='-1']),
button:not([disabled]):not([tabindex='-1']),
iframe:not([tabindex='-1']),
[tabindex]:not([tabindex='-1']),
[contentEditable=true]:not([tabindex='-1'])
{
/* your CSS for focusable elements goes here */
}
or a little more beautiful in SASS:
a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
&:not([tabindex='-1'])
{
/* your SCSS for focusable elements goes here */
}
}
I've added it as an answer, because that was, what I was looking for, when Google redirected me to this Stackoverflow question.
EDIT: There is one more selector, which is focusable:
[contentEditable=true]
However, this is used very rarely.
$focusable:
'a[href]',
'area[href]',
'button',
'details',
'input',
'iframe',
'select',
'textarea',
// these are actually case sensitive but i'm not listing out all the possible variants
'[contentEditable=""]',
'[contentEditable="true"]',
'[contentEditable="TRUE"]',
'[tabindex]:not([tabindex^="-"])',
':not([disabled])';
I'm creating a SCSS list of all focusable elements and I thought this might help someone due to this question's Google rank.
A few things to note:
I changed :not([tabindex="-1"]) to :not([tabindex^="-"]) because it's perfectly plausible to generate -2 somehow. Better safe than sorry right?
Adding :not([tabindex^="-"]) to all the other focusable selectors is completely pointless. When using [tabindex]:not([tabindex^="-"]) it already includes all elements that you'd be negating with :not!
I included :not([disabled]) because disabled elements can never be focusable. So again it's useless to add it to every single element.
The ally.js accessibility library provides an unofficial, test-based list here:
https://allyjs.io/data-tables/focusable.html
(NB: Their page doesn't say how often tests were performed.)
Maybe this one can help:
function focus(el){
el.focus();
return el==document.activeElement;
}
return value: true = success, false = failed
Reff:
https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
There is a much more elegant way to handle this:
Extend the element prototype like the sample below.
Then you can use it like:
element.isFocusable()
*Returns true if "element" is focusable and false if not.
/**
* Determining if an element can be focused on
* #return {Boolean}
*/
HTMLElement.prototype.isFocusable = function () {
var current = document.activeElement
if (current === this) return true
var protectEvent = (e) => e.stopImmediatePropagation()
this.addEventListener("focus", protectEvent, true)
this.addEventListener("blur", protectEvent, true)
this.focus({preventScroll:true})
var result = document.activeElement === this
this.blur()
if (current) current.focus({preventScroll:true})
this.removeEventListener("focus", protectEvent, true)
this.removeEventListener("blur", protectEvent, true)
return result
}
// A SIMPLE TEST
console.log(document.querySelector('a').isFocusable())
console.log(document.querySelector('a[href]').isFocusable())
<a>Not focusable</a>
Focusable