I am looking for a CSS selector for the following table:
Peter | male | 34
Susanne | female | 12
Is there any selector to match all TDs containing "male"?
If I read the specification correctly, no.
You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.
Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.
:contains() CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors
Using jQuery:
$('td:contains("male")')
You'd have to add a data attribute to the rows called data-gender with a male or female value and use the attribute selector:
HTML:
<td data-gender="male">...</td>
CSS:
td[data-gender="male"] { ... }
There is actually a very conceptual basis for why this hasn't been implemented. It is a combination of basically 3 aspects:
The text content of an element is effectively a child of that element
You cannot target the text content directly
CSS does not allow for ascension with selectors
These 3 together mean that by the time you have the text content you cannot ascend back to the containing element, and you cannot style the present text. This is likely significant as descending only allows for a singular tracking of context and SAX style parsing. Ascending or other selectors involving other axes introduce the need for more complex traversal or similar solutions that would greatly complicate the application of CSS to the DOM.
You could set content as data attribute and then use attribute selectors, as shown here:
/* Select every cell matching the word "male" */
td[data-content="male"] {
color: red;
}
/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
color: blue;
}
/* Select every cell containing "4" */
td[data-content*="4"] {
color: green;
}
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-content="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
You can also use jQuery to easily set the data-content attributes:
$(function(){
$("td").each(function(){
var $this = $(this);
$this.attr("data-content", $this.text());
});
});
As CSS lacks this feature you will have to use JavaScript to style cells by content. For example with XPath's contains:
var elms = document.evaluate( "//td[contains(., 'male')]", node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null )
Then use the result like so:
for ( var i=0 ; i < elms.snapshotLength; i++ ){
elms.snapshotItem(i).style.background = "pink";
}
https://jsfiddle.net/gaby_de_wilde/o7bka7Ls/9/
As of Jan 2021, there IS something that will do just this. :has() ... only one catch: this is not supported in any browser yet
Example: The following selector matches only elements that directly contain an child:
a:has(> img)
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
https://caniuse.com/?search=has
I'm afraid this is not possible, because the content is no attribute nor is it accessible via a pseudo class. The full list of CSS3 selectors can be found in the CSS3 specification.
For those who are looking to do Selenium CSS text selections, this script might be of some use.
The trick is to select the parent of the element that you are looking for, and then search for the child that has the text:
public static IWebElement FindByText(this IWebDriver driver, string text)
{
var list = driver.FindElement(By.CssSelector("#RiskAddressList"));
var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", text), list);
return ((System.Collections.ObjectModel.ReadOnlyCollection<IWebElement>)element)[0];
}
This will return the first element if there is more than one since it's always one element, in my case.
Excellent answers all around, but I think I can add something that worked for me in a practical scenario: exploiting the aria-label attribute for CSS.
For the readers that don't know: aria-label is an attribute that is used in conjunction with other similar attributes to let a screen-reader know what something is, in case someone with a visual impairment is using your website. Many websites add these attributes to elements with images or text in them, as "descriptors".
This makes it highly website-specific, but in case your element contains this, it's fairly simple to select that element using the content of the attribute:
HTML:
<td aria-label="male">Male</td>
<td aria-label="female">Female</td>
CSS:
td[aria-label="male"] {
outline: 1px dotted green;
}
This is technically the same thing as using the data-attribute solution, but this will work for you if you are not the author of the website, plus this is not some out-of-the-way solution that is specifically designed to support this use case; it's fairly common on its own. The one downside of it is that there's really no guarantee that your intended element will have this attribute present.
If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:
for ( td of document.querySelectorAll('td') ) {
console.debug("text:", td, td.innerText)
td.setAttribute('text', td.innerText)
}
for ( td of document.querySelectorAll('td[text="male"]') )
console.debug("male:", td, td.innerText)
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>12</td>
</tr>
</table>
Console output
text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male
Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:
cells = document.querySelectorAll('td');
console.log(cells);
[].forEach.call(cells, function (el) {
if(el.innerText.indexOf("male") !== -1){
//el.click(); click or any other option
console.log(el)
}
});
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-conten="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:
td.male { color: blue; }
td.female { color: pink; }
can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:
<td class="{{person.gender}}">
Just make sure that the content is only one word! Or you could even map to different CSS class names with:
<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">
For completeness, here's the data attribute approach:
<td data-gender="{{person.gender}}">
If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.
This, for example, will click on the first anchor that contains the words "Bad bear":
browser.click("a*=Bad Bear");
#voyager's answer about using data-* attribute (e.g. data-gender="female|male" is the most effective and standards compliant approach as of 2017:
[data-gender='male'] {background-color: #000; color: #ccc;}
Pretty much most goals can be attained as there are some albeit limited selectors oriented around text. The ::first-letter is a pseudo-element that can apply limited styling to the first letter of an element. There is also a ::first-line pseudo-element besides obviously selecting the first line of an element (such as a paragraph) also implies that it is obvious that CSS could be used to extend this existing capability to style specific aspects of a textNode.
Until such advocacy succeeds and is implemented the next best thing I could suggest when applicable is to explode/split words using a space deliminator, output each individual word inside of a span element and then if the word/styling goal is predictable use in combination with :nth selectors:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span>'.$value1.'</span>;
}
Else if not predictable to, again, use voyager's answer about using data-* attribute. An example using PHP:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span data-word="'.$value1.'">'.$value1.'</span>;
}
If you want to apply style to the content you want. Easy trick.
td { border: 1px solid black; }
td:empty { background: lime; }
td:empty::after { content: "male"; }
<table>
<tr>
<td>Peter</td>
<td><!--male--></td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
https://jsfiddle.net/hyda8kqz/
I find the attribute option to be your best bet if you don't want to use javascript or jquery.
E.g to style all table cells with the word ready, In HTML do this:
<td status*="ready">Ready</td>
Then in css:
td[status*="ready"] {
color: red;
}
Doing small Filter Widgets like this:
var searchField = document.querySelector('HOWEVER_YOU_MAY_FIND_IT')
var faqEntries = document.querySelectorAll('WRAPPING_ELEMENT .entry')
searchField.addEventListener('keyup', function (evt) {
var testValue = evt.target.value.toLocaleLowerCase();
var regExp = RegExp(testValue);
faqEntries.forEach(function (entry) {
var text = entry.textContent.toLocaleLowerCase();
entry.classList.remove('show', 'hide');
if (regExp.test(text)) {
entry.classList.add('show')
} else {
entry.classList.add('hide')
}
})
})
The syntax of this question looks like Robot Framework syntax.
In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead.
The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male
Related
I am looking for a CSS selector for the following table:
Peter | male | 34
Susanne | female | 12
Is there any selector to match all TDs containing "male"?
If I read the specification correctly, no.
You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.
Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.
:contains() CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors
Using jQuery:
$('td:contains("male")')
You'd have to add a data attribute to the rows called data-gender with a male or female value and use the attribute selector:
HTML:
<td data-gender="male">...</td>
CSS:
td[data-gender="male"] { ... }
There is actually a very conceptual basis for why this hasn't been implemented. It is a combination of basically 3 aspects:
The text content of an element is effectively a child of that element
You cannot target the text content directly
CSS does not allow for ascension with selectors
These 3 together mean that by the time you have the text content you cannot ascend back to the containing element, and you cannot style the present text. This is likely significant as descending only allows for a singular tracking of context and SAX style parsing. Ascending or other selectors involving other axes introduce the need for more complex traversal or similar solutions that would greatly complicate the application of CSS to the DOM.
You could set content as data attribute and then use attribute selectors, as shown here:
/* Select every cell matching the word "male" */
td[data-content="male"] {
color: red;
}
/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
color: blue;
}
/* Select every cell containing "4" */
td[data-content*="4"] {
color: green;
}
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-content="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
You can also use jQuery to easily set the data-content attributes:
$(function(){
$("td").each(function(){
var $this = $(this);
$this.attr("data-content", $this.text());
});
});
As CSS lacks this feature you will have to use JavaScript to style cells by content. For example with XPath's contains:
var elms = document.evaluate( "//td[contains(., 'male')]", node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null )
Then use the result like so:
for ( var i=0 ; i < elms.snapshotLength; i++ ){
elms.snapshotItem(i).style.background = "pink";
}
https://jsfiddle.net/gaby_de_wilde/o7bka7Ls/9/
As of Jan 2021, there IS something that will do just this. :has() ... only one catch: this is not supported in any browser yet
Example: The following selector matches only elements that directly contain an child:
a:has(> img)
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
https://caniuse.com/?search=has
I'm afraid this is not possible, because the content is no attribute nor is it accessible via a pseudo class. The full list of CSS3 selectors can be found in the CSS3 specification.
For those who are looking to do Selenium CSS text selections, this script might be of some use.
The trick is to select the parent of the element that you are looking for, and then search for the child that has the text:
public static IWebElement FindByText(this IWebDriver driver, string text)
{
var list = driver.FindElement(By.CssSelector("#RiskAddressList"));
var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", text), list);
return ((System.Collections.ObjectModel.ReadOnlyCollection<IWebElement>)element)[0];
}
This will return the first element if there is more than one since it's always one element, in my case.
Excellent answers all around, but I think I can add something that worked for me in a practical scenario: exploiting the aria-label attribute for CSS.
For the readers that don't know: aria-label is an attribute that is used in conjunction with other similar attributes to let a screen-reader know what something is, in case someone with a visual impairment is using your website. Many websites add these attributes to elements with images or text in them, as "descriptors".
This makes it highly website-specific, but in case your element contains this, it's fairly simple to select that element using the content of the attribute:
HTML:
<td aria-label="male">Male</td>
<td aria-label="female">Female</td>
CSS:
td[aria-label="male"] {
outline: 1px dotted green;
}
This is technically the same thing as using the data-attribute solution, but this will work for you if you are not the author of the website, plus this is not some out-of-the-way solution that is specifically designed to support this use case; it's fairly common on its own. The one downside of it is that there's really no guarantee that your intended element will have this attribute present.
If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:
for ( td of document.querySelectorAll('td') ) {
console.debug("text:", td, td.innerText)
td.setAttribute('text', td.innerText)
}
for ( td of document.querySelectorAll('td[text="male"]') )
console.debug("male:", td, td.innerText)
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>12</td>
</tr>
</table>
Console output
text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male
Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:
cells = document.querySelectorAll('td');
console.log(cells);
[].forEach.call(cells, function (el) {
if(el.innerText.indexOf("male") !== -1){
//el.click(); click or any other option
console.log(el)
}
});
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-conten="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:
td.male { color: blue; }
td.female { color: pink; }
can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:
<td class="{{person.gender}}">
Just make sure that the content is only one word! Or you could even map to different CSS class names with:
<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">
For completeness, here's the data attribute approach:
<td data-gender="{{person.gender}}">
If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.
This, for example, will click on the first anchor that contains the words "Bad bear":
browser.click("a*=Bad Bear");
#voyager's answer about using data-* attribute (e.g. data-gender="female|male" is the most effective and standards compliant approach as of 2017:
[data-gender='male'] {background-color: #000; color: #ccc;}
Pretty much most goals can be attained as there are some albeit limited selectors oriented around text. The ::first-letter is a pseudo-element that can apply limited styling to the first letter of an element. There is also a ::first-line pseudo-element besides obviously selecting the first line of an element (such as a paragraph) also implies that it is obvious that CSS could be used to extend this existing capability to style specific aspects of a textNode.
Until such advocacy succeeds and is implemented the next best thing I could suggest when applicable is to explode/split words using a space deliminator, output each individual word inside of a span element and then if the word/styling goal is predictable use in combination with :nth selectors:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span>'.$value1.'</span>;
}
Else if not predictable to, again, use voyager's answer about using data-* attribute. An example using PHP:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span data-word="'.$value1.'">'.$value1.'</span>;
}
If you want to apply style to the content you want. Easy trick.
td { border: 1px solid black; }
td:empty { background: lime; }
td:empty::after { content: "male"; }
<table>
<tr>
<td>Peter</td>
<td><!--male--></td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
https://jsfiddle.net/hyda8kqz/
I find the attribute option to be your best bet if you don't want to use javascript or jquery.
E.g to style all table cells with the word ready, In HTML do this:
<td status*="ready">Ready</td>
Then in css:
td[status*="ready"] {
color: red;
}
Doing small Filter Widgets like this:
var searchField = document.querySelector('HOWEVER_YOU_MAY_FIND_IT')
var faqEntries = document.querySelectorAll('WRAPPING_ELEMENT .entry')
searchField.addEventListener('keyup', function (evt) {
var testValue = evt.target.value.toLocaleLowerCase();
var regExp = RegExp(testValue);
faqEntries.forEach(function (entry) {
var text = entry.textContent.toLocaleLowerCase();
entry.classList.remove('show', 'hide');
if (regExp.test(text)) {
entry.classList.add('show')
} else {
entry.classList.add('hide')
}
})
})
The syntax of this question looks like Robot Framework syntax.
In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead.
The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male
I am looking for a CSS selector for the following table:
Peter | male | 34
Susanne | female | 12
Is there any selector to match all TDs containing "male"?
If I read the specification correctly, no.
You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.
Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.
:contains() CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors
Using jQuery:
$('td:contains("male")')
You'd have to add a data attribute to the rows called data-gender with a male or female value and use the attribute selector:
HTML:
<td data-gender="male">...</td>
CSS:
td[data-gender="male"] { ... }
There is actually a very conceptual basis for why this hasn't been implemented. It is a combination of basically 3 aspects:
The text content of an element is effectively a child of that element
You cannot target the text content directly
CSS does not allow for ascension with selectors
These 3 together mean that by the time you have the text content you cannot ascend back to the containing element, and you cannot style the present text. This is likely significant as descending only allows for a singular tracking of context and SAX style parsing. Ascending or other selectors involving other axes introduce the need for more complex traversal or similar solutions that would greatly complicate the application of CSS to the DOM.
You could set content as data attribute and then use attribute selectors, as shown here:
/* Select every cell matching the word "male" */
td[data-content="male"] {
color: red;
}
/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
color: blue;
}
/* Select every cell containing "4" */
td[data-content*="4"] {
color: green;
}
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-content="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
You can also use jQuery to easily set the data-content attributes:
$(function(){
$("td").each(function(){
var $this = $(this);
$this.attr("data-content", $this.text());
});
});
As CSS lacks this feature you will have to use JavaScript to style cells by content. For example with XPath's contains:
var elms = document.evaluate( "//td[contains(., 'male')]", node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null )
Then use the result like so:
for ( var i=0 ; i < elms.snapshotLength; i++ ){
elms.snapshotItem(i).style.background = "pink";
}
https://jsfiddle.net/gaby_de_wilde/o7bka7Ls/9/
As of Jan 2021, there IS something that will do just this. :has() ... only one catch: this is not supported in any browser yet
Example: The following selector matches only elements that directly contain an child:
a:has(> img)
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
https://caniuse.com/?search=has
I'm afraid this is not possible, because the content is no attribute nor is it accessible via a pseudo class. The full list of CSS3 selectors can be found in the CSS3 specification.
For those who are looking to do Selenium CSS text selections, this script might be of some use.
The trick is to select the parent of the element that you are looking for, and then search for the child that has the text:
public static IWebElement FindByText(this IWebDriver driver, string text)
{
var list = driver.FindElement(By.CssSelector("#RiskAddressList"));
var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", text), list);
return ((System.Collections.ObjectModel.ReadOnlyCollection<IWebElement>)element)[0];
}
This will return the first element if there is more than one since it's always one element, in my case.
Excellent answers all around, but I think I can add something that worked for me in a practical scenario: exploiting the aria-label attribute for CSS.
For the readers that don't know: aria-label is an attribute that is used in conjunction with other similar attributes to let a screen-reader know what something is, in case someone with a visual impairment is using your website. Many websites add these attributes to elements with images or text in them, as "descriptors".
This makes it highly website-specific, but in case your element contains this, it's fairly simple to select that element using the content of the attribute:
HTML:
<td aria-label="male">Male</td>
<td aria-label="female">Female</td>
CSS:
td[aria-label="male"] {
outline: 1px dotted green;
}
This is technically the same thing as using the data-attribute solution, but this will work for you if you are not the author of the website, plus this is not some out-of-the-way solution that is specifically designed to support this use case; it's fairly common on its own. The one downside of it is that there's really no guarantee that your intended element will have this attribute present.
If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:
for ( td of document.querySelectorAll('td') ) {
console.debug("text:", td, td.innerText)
td.setAttribute('text', td.innerText)
}
for ( td of document.querySelectorAll('td[text="male"]') )
console.debug("male:", td, td.innerText)
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>12</td>
</tr>
</table>
Console output
text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male
Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:
cells = document.querySelectorAll('td');
console.log(cells);
[].forEach.call(cells, function (el) {
if(el.innerText.indexOf("male") !== -1){
//el.click(); click or any other option
console.log(el)
}
});
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-conten="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:
td.male { color: blue; }
td.female { color: pink; }
can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:
<td class="{{person.gender}}">
Just make sure that the content is only one word! Or you could even map to different CSS class names with:
<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">
For completeness, here's the data attribute approach:
<td data-gender="{{person.gender}}">
If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.
This, for example, will click on the first anchor that contains the words "Bad bear":
browser.click("a*=Bad Bear");
#voyager's answer about using data-* attribute (e.g. data-gender="female|male" is the most effective and standards compliant approach as of 2017:
[data-gender='male'] {background-color: #000; color: #ccc;}
Pretty much most goals can be attained as there are some albeit limited selectors oriented around text. The ::first-letter is a pseudo-element that can apply limited styling to the first letter of an element. There is also a ::first-line pseudo-element besides obviously selecting the first line of an element (such as a paragraph) also implies that it is obvious that CSS could be used to extend this existing capability to style specific aspects of a textNode.
Until such advocacy succeeds and is implemented the next best thing I could suggest when applicable is to explode/split words using a space deliminator, output each individual word inside of a span element and then if the word/styling goal is predictable use in combination with :nth selectors:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span>'.$value1.'</span>;
}
Else if not predictable to, again, use voyager's answer about using data-* attribute. An example using PHP:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span data-word="'.$value1.'">'.$value1.'</span>;
}
If you want to apply style to the content you want. Easy trick.
td { border: 1px solid black; }
td:empty { background: lime; }
td:empty::after { content: "male"; }
<table>
<tr>
<td>Peter</td>
<td><!--male--></td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
https://jsfiddle.net/hyda8kqz/
I find the attribute option to be your best bet if you don't want to use javascript or jquery.
E.g to style all table cells with the word ready, In HTML do this:
<td status*="ready">Ready</td>
Then in css:
td[status*="ready"] {
color: red;
}
Doing small Filter Widgets like this:
var searchField = document.querySelector('HOWEVER_YOU_MAY_FIND_IT')
var faqEntries = document.querySelectorAll('WRAPPING_ELEMENT .entry')
searchField.addEventListener('keyup', function (evt) {
var testValue = evt.target.value.toLocaleLowerCase();
var regExp = RegExp(testValue);
faqEntries.forEach(function (entry) {
var text = entry.textContent.toLocaleLowerCase();
entry.classList.remove('show', 'hide');
if (regExp.test(text)) {
entry.classList.add('show')
} else {
entry.classList.add('hide')
}
})
})
The syntax of this question looks like Robot Framework syntax.
In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead.
The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male
Suppose I have the following table:
+----------+
| A | B |
+----------+
| 1 | 2 |
+----------+
I want to make so that when I hover over A that 1 gets certain css styles, ditto for B and 2. Is there a way to do this without using js?
Here's a fiddle to see what I mean
With this markup and pure CSS it's not possible because you would need to use td:hover to apply the CSS rule on mouseover, and there is no selector that lets you travel up the DOM tree (which would be necessary as you want to target cells that live in a different branch from the one being hovered).
If you can modify then a solution such as Dustin's can work; if you can use JS then it's also a matter of sprinkling a little jQuery on the table:
$("td").on("mouseenter mouseout", function() {
var $this = $(this);
$this.closest("table").find("td:nth-child(" + ($this.index() + 1) + ")")
.toggleClass("hover");
});
If you can change the markup, here's a response jsfiddle to do this with CSS.
http://jsfiddle.net/dBrd2/
Edit: Ah, but I see you replied to my comment and said you didn't want to. Anyways, just an idea if you reconsider.
you can create a class called .hover, and do like this for adding the style to all the td's with the same class
$("td.fir").bind("mouseenter", function(){
$(".fir").addClass("hover");
});
$("td.fir").bind("mouseleave", function(){
$(".fir").removeClass("hover");
});
Hi you can do as like this
Css
td {
position: relative;
border: 1px solid black;
padding: 50px;
}
tr .fir{
background:red;
}
table:hover .fir{
background:green;
}
HTML
<table>
<tr>
<td class="fir">a</td>
<td class="sec">b</td>
</tr>
<tr>
<td class="fir">1</td>
<td class="sec">2</td>
</tr>
</table>
Live Demo here http://jsfiddle.net/rohitazad/en5rB/3/
Terr!
HTML::Table has pretty good flexibility to form HTML-tables from perl data structures, but i did not found proper way how to have th-tags different than ordinary cells (td) in same column. Or let me rephrase: if i set column class, i'd like to set it only for data rows, not for header row.
use strict;
use warnings;
use HTML::Table;
my $table = new HTML::Table(
-head=> ['one', 'two', 'eleven'],
-data=> [ ['yki', 'kaki', 'kommi'],
['yy', 'kaa', 'koo'] ]
);
$table->setColClass(1, 'class');
$table->setSectionColClass('tbody', 0, 2, 'class2');
print $table;
And output is:
<table>
<tbody>
<tr><th class="class">one</th><th class="class2">two</th><th>eleven</th></tr>
<tr><td class="class">yki</td><td class="class2">kaki</td><td>kommi</td></tr>
<tr><td class="class">yy</td><td class="class2">kaa</td><td>koo</td></tr>
</tbody>
</table>
Output i am looking for:
<table>
<tbody>
<tr><th>one</th><th>two</th><th>eleven</th></tr>
<tr><td class="class">yki</td><td class="class2">kaki</td><td>kommi</td></tr>
<tr><td class="class">yy</td><td class="class2">kaa</td><td>koo</td></tr>
</tbody>
</table>
There are section level methods, but th belongs also in tbody. Tables may be pretty complex, so i'd like to avoid iterating over the heading row and hope to find a decent way. Is there?
Might be easies to just tweak your CSS a bit. Presumably you have something like this in your stylesheet:
.class { /* Some pretty stuff */ }
So just change the selector to adjust how the header and body cells are styled:
td.class { /* The styles you want applied to body cells go here. */ }
th.class { /* And the styles for header cells (if any) go here. */ }
If you don't want any styling applied to the header cells then include the td.class { } bit in your stylesheet and leave the th.class { } out; there's nothing wrong with having a CSS class attached to an element that doesn't match anything in your stylesheets.
I can't set my table row as link to something. I can use only css and html. I tried different things from div in row to something another, but still can't make it works.
You have two ways to do this:
Using javascript:
<tr onclick="document.location = 'links.html';">
Using anchors:
<tr><td>text</td><td>text</td></tr>
I made the second work using:
table tr td a {
display:block;
height:100%;
width:100%;
}
To get rid of the dead space between columns:
table tr td {
padding-left: 0;
padding-right: 0;
}
Here is a simple demo of the second example: DEMO
I made myself a custom jquery function:
Html
<tr data-href="site.com/whatever">
jQuery
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
Easy and perfect for me. Hopefully it helps you.
(I know OP want CSS and HTML only, but consider jQuery)
Edit
Agreed with Matt Kantor using data attr. Edited answer above
If you're on a browser that supports it you can use CSS to transform the <a> into a table row:
.table-row { display: table-row; }
.table-cell { display: table-cell; }
<div style="display: table;">
<a href="..." class="table-row">
<span class="table-cell">This is a TD... ish...</span>
</a>
</div>
Of course, you're limited to not putting block elements inside the <a>.
You also can't mix this in with a regular <table>
If you have to use a table, you can put a link into each table cell:
<table>
<tbody>
<tr>
<td>John Smith</td>
<td>123 Fake St</td>
<td>90210</td>
</tr>
<tr>
<td>Peter Nguyen</td>
<td>456 Elm Ave</td>
<td>90210</td>
</tr>
</tbody>
</table>
And make the links fill up the entire cells:
table tbody tr td a {
display: block;
width: 100%;
height: 100%;
}
If you are able to use <div>s instead of a table, your HTML can be a lot simpler, and you won't get "gaps" in the links, between the table cells:
<div class="myTable">
<a href="person1.html">
<span>John Smith</span>
<span>123 Fake St</span>
<span>90210</span>
</a>
<a href="person2.html">
<span>Peter Nguyen</span>
<span>456 Elm Ave</span>
<span>90210</span>
</a>
</div>
Here is the CSS that goes with the <div> method:
.myTable {
display: table;
}
.myTable a {
display: table-row;
}
.myTable a span {
display: table-cell;
padding: 2px; /* this line not really needed */
}
The usual way is to assign some JavaScript to the onClick attribute of the TR element.
If you can't use JavaScript, then you must use a trick:
Add the same link to each TD of the same row (the link must be the outermost element in the cell).
Turn links into block elements: a { display: block; width: 100%; height: 100%; }
The latter will force the link to fill the whole cell so clicking anywhere will invoke the link.
Answer from sirwilliam fits me best. I improved the Javascript with support for hotkey Ctrl + LeftClick (opens page in new tab). Event ctrlKey is used by PC's, metaKey by Mac.
Javascript
$('body').on('mousedown', 'tr[url]', function(e){
var click = e.which;
var url = $(this).attr('url');
if(url){
if(click == 2 || (click == 1 && (e.ctrlKey || e.metaKey))){
window.open(url, '_blank');
window.focus();
}
else if(click == 1){
window.location.href = url;
}
return true;
}
});
Example
http://jsfiddle.net/vlastislavnovak/oaqo2kgs/
You can't wrap a <td> element with an <a> tag, but you can accomplish similar functionality by using the onclick event to call a function. An example is found here, something like this function:
<script type="text/javascript">
function DoNav(url)
{
document.location.href = url;
}
</script>
And add it to your table like this:
<tr onclick="DoNav('http://stackoverflow.com/')"><td></td></tr>
I know this question is already answered but I still don't like any solution on this page. For the people who use JQuery I made a final solution which enables you to give the table row almost the same behaviour as the <a> tag.
This is my solution:
jQuery You can add this for example to a standard included javascript file
$('body').on('mousedown', 'tr[url]', function(e){
var click = e.which;
var url = $(this).attr('url');
if(url){
if(click == 1){
window.location.href = url;
}
else if(click == 2){
window.open(url, '_blank');
window.focus();
}
return true;
}
});
HTML Now you can use this on any <tr> element inside your HTML
<tr url="example.com">
<td>value</td>
<td>value</td>
<td>value</td>
<tr>
When i want simulate a <tr> with a link but respecting the html standards, I do this.
HTML:
<table>
<tr class="trLink">
<td>
Something
</td>
</tr>
</table>
CSS:
tr.trLink {
cursor: pointer;
}
tr.trLink:hover {
/*TR-HOVER-STYLES*/
}
tr.trLink a{
display: block;
height: 100%;
width: 100%;
}
tr.trLink:hover a{
/*LINK-HOVER-STYLES*/
}
In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.
Hope can help someone.
Fiddle HERE
This saves you having to duplicate the link in the tr - just fish it out of the first a.
$(".link-first-found").click(function() {
var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});
//Style
.trlink {
color:blue;
}
.trlink:hover {
color:red;
}
<tr class="trlink" onclick="function to navigate to a page goes here">
<td>linktext</td>
</tr>
Something along these lines perhaps? Though it does use JS, but that's only way to make a row (tr) clickable.
Unless you have a single cell with an anchor tag that fills the entire cell.
And then, you shouldn't be using a table anyhow.
After reading this thread and some others I came up with the following solution in javascript:
function trs_makelinks(trs) {
for (var i = 0; i < trs.length; ++i) {
if (trs[i].getAttribute("href") != undefined) {
var tr = trs[i];
tr.onclick = function () { window.location.href = this.getAttribute("href"); };
tr.onkeydown = function (e) {
var e = e || window.event;
if ((e.keyCode === 13) || (e.keyCode === 32)) {
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
this.click();
}
};
tr.role = "button";
tr.tabIndex = 0;
tr.style.cursor = "pointer";
}
}
}
/* It could be adapted for other tags */
trs_makelinks(document.getElementsByTagName("tr"));
trs_makelinks(document.getElementsByTagName("td"));
trs_makelinks(document.getElementsByTagName("th"));
To use it put the href in tr/td/th that you desire to be clickable like: <tr href="http://stackoverflow.com">.
And make sure the script above is executed after the tr element is created (by its placement or using event handlers).
The downside is it won't totally make the TRs behave as links like with divs with display: table;, and they won't be keyboard-selectable or have status text. Edit: I made keyboard navigation work by setting onkeydown, role and tabIndex, you could remove that part if only mouse is needed. They won't show the URL in statusbar on hovering though.
You can style specifically the link TRs with "tr[href]" CSS selector.
I have another way. Especially if you need to post data using jQuery
$(document).on('click', '#tablename tbody tr', function()
{
var test="something";
$.post("ajax/setvariable.php", {ID: this.id, TEST:test}, function(data){
window.location.href = "http://somepage";
});
});
Set variable sets up variables in SESSIONS which the page you are going to can read and act upon.
I would really like a way of posting straight to a window location, but I do not think it is possible.
Thanks for this. You can change the hover icon by assigning a CSS class to the row like:
<tr class="pointer" onclick="document.location = 'links.html';">
and the CSS looks like:
<style>
.pointer { cursor: pointer; }
</style>
This method is here to give you a choice. Old css trick: filling the parent with position absolute.
<table>
<tr style=position:relative>
<td><a href=# style=position:absolute;inset:0></a>some
<td>cells
<td>in
<td>a row
</table>
inset:0 is a shorthand for top:0;right:0;bottom:0;left:0
we put <a> inside first <td> because this is a good chance to keep validity: only <td> can be a child of <tr>. But you can place it anywhere in the table and it will work.
Can you add an A tag to the row?
<tr><td>
</td></tr>
Is this what you're asking?