Attach an image to any word - css

I'd like to attach images to specific words but cannot find the right CSS selector to do so.
I have a portion of my site which displays data as it's pulled from a database, so adding classes or id's to certain words is not an option for me. I need the css to simply display a background image wherever that word (or in this case, name) is found on the page.
For example, in the following (which is pulled from a database):
<td class="data1"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Patrick</font></td>
I would like to add a background image where the name Patrick is found.
I tried variations of,
td[.table1 *='Parick'] {
background-image:url(../images/accept.png);
but that didn't get me anywhere. And since it's not in a <span> or <div> or even a link, I can't figure it out. If you have any ideas or a jQuery workaround, please let me know. Thanks!

If you can guarantee the names only appear as the only text nodes in elements, you can use a simple jQuery selector...
$(':contains("Patrick")').addClass('name');
jsFiddle.
If there may be surrounding whitespace and/or the search should be case insensitive, try...
$('*').filter(function() {
return $.trim($(this).text()).toLowerCase() == 'patrick';
}).addClass('name');
jsFiddle.
If you need to find the name anywhere in any text node and then you need to wrap it with an element, try...
$('*').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
var node = this;
this.data.replace(/\bPatrick\b/i, function(all, offset) {
var chunk = node.splitText(offset);
chunk.data = chunk.data.substr(all.length);
var span = $('<span />', {
'class': 'name',
text: all
});
$(node).after(span);
});
});​
jsFiddle.
I would recommend using the third example.

Related

Targetting element:only-child with no sibling text node [duplicate]

I would like to select anchor tags only when they're completely by themselves, that way I can make those look like buttons, without causing anchors within sentences to look like buttons. I don't want to add an extra class because this is going within a CMS.
I originally was trying this:
article p a:first-child:last-child {
background-color: #b83634;
color: white;
text-transform: uppercase;
font-weight: bold;
padding: 4px 24px;
}
But it doesn't work because text content isn't considered as criteria for :first-child or :last-child.
I would like to match
<p><a href='#'>Link</a></p>
but not
<p><a href='#'>Link</a> text content</p>
or
<p>text content <a href='#'>Link</a></p>
Is this possible with CSS?
The simple answer is: no, you can't.
As explained here, here and here, there is no CSS selector that applies to the text nodes.
If you could use jQuery, take a look at the contains selector.
Unfortunately no, you can't.
You have to use JS by it self or any librady of it to interact with content of elements and found where is each element in the content.
If you wish me to update my answer with a JS example prease ask for it.
I don't think it's generally possible, but you can come close. Here are some helpful places to start:
The Only Child Selector which would allow you to select all a elements which have no siblings like so a:only-child {/* css */}. See more here. (Also see edit)
The Not Selector which would allow you to exclude some elements perhaps using something along the lines of :not(p) > a {/* css */} which should select all anchors not in a paragraph. See some helpful information here.
Combining selectors to be as specific as possible. You might want all anchors not in an h1 and all anchors not in a p.
Example:
The final product might look like this:
a:only-child, :not(p) > a {/* css */}
This should select all anchors that are only children and anchors that are not in a paragraph.
Final note:
You may want to consider making the buttons actual button or input tags to make your life easier. Getting the HTML right first usually makes the CSS simpler.
Edit: the only child ignores the text, so that's pretty much useless here. I guess it's less doable than I thought.
jQuery Code Example:
// this will select '<p><a></a></p>' or '<p><a></a>text</p>'
// but not '<p><a></a><a></a></p>'
$('p').has('a:only-child').each(function() {
const p = $(this); // jQuerify
let hasalsotext = false;
p.contents().each(function(){
if ((this.nodeType === 3) && (this.nodeValue.trim() !== "")) {
hasalsotext = true;
return false; // break
}
});
if (!hasalsotext) {
$('a', p).addClass('looks-like-a-button');
}
});

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 apply CSS to second word in a string?

If I have the following string: John Smith, how could I use CSS to set font-weight: bold on the second word in order to achieve: John Smith.
Can this be done in pure CSS?
Update: I am retrieving user's name from the server, so in my template it is #{user.profile.name}.
Since a js solution was suggested and pure CSS isn't presently possible: Live demo (click).
Sample markup:
<p class="bold-second-word">John Smith</p>
<p class="bold-second-word">This guy and stuff.</p>
JavaScript:
var toBold = document.getElementsByClassName('bold-second-word');
for (var i=0; i<toBold.length; ++i) {
boldSecondWord(toBold[i]);
}
function boldSecondWord(elem) {
elem.innerHTML = elem.textContent.replace(/\w+ (\w+)/, function(s, c) {
return s.replace(c, '<b>'+c+'</b>');
});
}
It cannot be done in pure CSS, sorry. But if you are willing to accept a JavaScript fix, then you might want to look into something like this:
Find the start and end index of the second word in the element's textContent.
Add contenteditable attribute to element.
Use the Selection API to select that range.
Use execCommand with the bold command.
Remove contenteditable attribute.
EDIT: (just saw your edit) I agree this is a bit too hack-y for most uses. Perhaps you'd be better off saving what the last name is as meta-data?
It seems to be impossible by using only pure CSS. However, with a bit of JS you could get there pretty easily:
const phrases = document.querySelectorAll('.bold-second-word');
for (const phrase of phrases) {
const words = phrase.innerHTML.split(' ');
words[1] = `<b>${words[1]}</b>`; // this would return the second word
phrase.innerHTML = words.join(' ');
}
<p class="bold-second-word">John Smith</p>
<p class="bold-second-word">Aaron Kelly Jones</p>

CSS3: set background image to rel attribute value

I'm looking to set the background-image (or even render an image via the pseudo elements :after or :before) to the value, which will be a URL, of a rel attribute, but only in certain cases (this is a cloud file listing). For example:
HTML:
<div class="icon ${fileExtension}" rel="${fileURL}"></div>
It would be great if I could do something like this:
CSS:
.icon.png,
.icon.jpg,
.icon.jpeg,
.icon.bmp,
.icon.gif { background-image: attr(rel,url); }
... but obviously that doesn't work as, if I'm not mistaken, the attr() CSS function only works inside pseudo element blocks.
I know there are ways of doing this using conditional JSP or even jQuery logic, but I'd like to figure out a neat way of doing it via CSS3, since I'm only concerned with modern browsers at the moment anyway.
Also, I don't want to explicitly set the background image to the URL or create an <img> element, because by default if the file is not a supported image, I'd rather display a predetermined set of icons.
Using
.icon:after{ content: ""attr(rel)""; }
displays the rel value as text.
A jQuery solution is to add the background-image (taken from the rel value) as inline CSS:
jQuery(function($) {
$('.icon').each(function() {
var $this = $(this);
$this.css('background-image', 'url(' + $this.attr('rel') + ')');
});
});
I've tried to do something using jQuery but i don't exactly understand what you want so i can't go on with my code. So far i've done only this.
EDITED I hope it's exactly what you need
$(function(){
var terms = new Array('png','jpg','jpeg','bmp','gif');
$('.icon').each(function(){
var t = $(this),
rel = t.attr('rel'),
cls = t.attr('class');
cls = cls.split(' ');
for (var i=0; i < terms.length; i++) {
if (terms[i] == cls[1]) {
t.css('background-image','url('+rel+')');
}
}
});
});
if you can give me a better example, to undestand exactly what you want, i hope somebody from here will be able to solve your problem.
Regards,
Stefan
I've decided to go the jQuery route, and used a combination of #ryanve and #stefanz answers. Thanks guys
$(document).ready(function() {
$(".png,.jpg,.jpeg,.bmp,.gif,.tiff").each(function(n) {
var bg = 'url(' + $(this).attr("rel") + ')';
$(this).css('background-image', bg);
});
});
I think this is relatively neat/concise and works well for my needs. Feel free to comment on efficiency, methodology, etc.

CSS text-transform capitalize on all caps

Here is my HTML:
small caps &
ALL CAPS
Here is my CSS:
.link {text-transform: capitalize;}
The output is:
Small Caps & ALL CAPS
and I want the output to be:
Small Caps & All Caps
Any ideas?
You can almost do it with:
.link {
text-transform: lowercase;
}
.link:first-letter,
.link:first-line {
text-transform: uppercase;
}
It will give you the output:
Small Caps
All Caps
There is no way to do this with CSS, you could use PHP or Javascript for this.
PHP example:
$text = "ALL CAPS";
$text = ucwords(strtolower($text)); // All Caps
jQuery example (it's a plugin now!):
// Uppercase every first letter of a word
jQuery.fn.ucwords = function() {
return this.each(function(){
var val = $(this).text(), newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
}
$(this).text(newVal);
});
}
$('a.link').ucwords();​
Convert with JavaScript using .toLowerCase() and capitalize would do the rest.
Interesting question!
capitalize transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. Not even the :first-letter pseudo-class will cut it (because it applies to the first letter of each element, not each word), and I can't see a way of combining lowercase and capitalize to get the desired outcome.
So as far as I can see, this is indeed impossible to do with CSS.
#Harmen shows good-looking PHP and jQuery workarounds in his answer.
I'd like to sugest a pure CSS solution that is more useful than the first letter solution presented but is also very similar.
.link {
text-transform: lowercase;
display: inline-block;
}
.link::first-line {
text-transform: capitalize;
}
<div class="link">HELLO WORLD!</div>
<p class="link">HELLO WORLD!</p>
HELLO WORLD! ( now working! )
Although this is limited to the first line it may be useful for more use cases than the first letter solution since it applies capitalization to the whole line and not only the first word. (all words in the first line)
In the OP's specific case this could have solved it.
Notes: As mentioned in the first letter solution comments, the order of the CSS rules is important! Also note that I changed the <a> tag for a <div> tag because for some reason the pseudo-element ::first-line doesn't work with <a> tags natively but either <div> or <p> are fine.
EDIT: the <a> element will work if display: inline-block; is added to the .link class. Thanks to Dave Land for spotting that!
New Note: if the text wraps it will loose the capitalization because it is now in fact on the second line (first line is still ok).
JavaScript:
var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
links[i].innerHTML = links[i].innerHTML.toLowerCase();
}
CSS:
.link { text-transform: capitalize; }
What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.
captialize only effects the first letter of the word. http://www.w3.org/TR/CSS21/text.html#propdef-text-transform
You can do it with css first-letter!
eg I wanted it for the Menu:
a {display:inline-block; text-transorm:uppercase;}
a::first-letter {font-size:50px;}
It only runs with block elements - therefore the inline-block!
May be useful for java and jstl.
Initialize variable with localized message.
After that it is possible to use it in jstl toLowerCase function.
Transform with CSS.
In JSP
1.
<fmt:message key="some.key" var="item"/>
2.
<div class="content">
${fn:toLowerCase(item)}
</div>
In CSS
3.
.content {
text-transform:capitalize;
}
If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.
After researching a lot I found jquery function/expression to change text in first letter in uppercase only, I modify that code accordingly to make it workable for input field. When you will write something in input field and then move to another filed or element, the text of that field will change with 1st-letter capitalization only. No matter user type text in complete lower or upper case capitalization:
Follow this code:
Step-1: Call jquery library in html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Step-2: Write code to change text of input fields:
<script>
$(document).ready(function(){
$("#edit-submitted-first-name,#edit-submitted-last-name,#edit-submitted-company-name, #edit-submitted-city").focusout(function(){
var str=$(this).val();
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
$(this).val(str);
});});
</script>
Step-3: Create HTML input fields with same id's you use in jquery code like:
<input type="text" id="edit-submitted-first-name" name="field name">
The id of this input field is: edit-submitted-first-name (It using in jquery code in step-2)
**Result:
Make sure the text will change after you move your focus from that input field at another element. Because we using focus out event of jquery here.
Result should like this: User Type: "thank you" it will change with "Thank You".
**
Best of luck
The PHP solution, in backend:
$string = 'UPPERCASE';
$lowercase = strtolower($string);
echo ucwords($lowercase);
I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.
Regex solutions are the fastest for sure.
Here is the jsPerf: https://jsperf.com/capitalize-jwaz
There are 2 regex solutions.
The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.
If you only want to capitalize letters that are preceded by a space then use the second regex
/(^[a-z]|\s[a-z])/g
if you are using jQuery; this is one a way to do it:
$('.link').each(function() {
$(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});
Here is an easier to read version doing the same thing:
//Iterate all the elements in jQuery object
$('.link').each(function() {
//get text from element and make it lower-case
var string = $(this).text().toLowerCase();
//set element text to the new string that is lower-case
$(this).text(string);
//set the css to capitalize
$(this).css('text-transform','capitalize');
});
Demo
all wrong it does exist --> font-variant: small-caps;
text-transform:capitalize; just the first letter cap

Resources