This question already has answers here:
Change last letter color
(8 answers)
Closed 9 years ago.
I am trying to apply some css to the current viewed menu item on a WordPress site. I can apply css to the whole item, but want to apply something to specifically just the last character.
Does anyone have any thoughts on how to go about this?
Thanks.
The is no cross browser solution to achieve it using pure CSS.
You can either using PHP or javascript to get the last character and style it or you can wrap that last character in another element like <span> and style it using css as normally.
EDIT: Here is the javascript approach:
<p class="test">This is a test</p>
var targets = document.getElementsByClassName('test');
for(i=0; i<targets.length; i++) {
var html = targets[i].innerHTML;
targets[i].innerHTML = html.substr(0, html.length-1)
+ "<span class='lastChar'>"
+ targets[i].innerHTML.substr(-1)
+ "</span>";
}
Fiddle Demo
As Felix said, there is no cross browser solution to achieve it using pure CSS. I would reccommend writing simple js code to split menu item and add span with class to last letter.
$('document').ready(function() {
var item = $('.current-menu-item').children().html();
$('.current-menu-item').children().html(item.substr(0, item.length - 1) + '<span class="last">' + item.substr(-1) + '</span>');
});
Related
I have html like this:
<a id="fixed">01</a>
<a id="fixed">02</a>
<a id="fixed">03</a>
<span>001</span>
<span>002</span>
<span>003</span>
Now I want to select the 002 element:
<span>002</span>
I used a#fixed:has(>span) to get the last three a elements, but I can't continue to use :nth-child(2) to select the second of them.
Using javascript code selectAll()[1].parentNode is a practical way.
But I need to use it in XPath, so I'm looking for a pure CSS selector to get it.
Is it because :has() cannot be used with :nth-child() or :nth-of-type()?
How to select one of several parent elements with the same characteristics of child elements?
PS: Only use pure CSS.
Looking forward to your answer, thank you:)
Thank you for comments.
An id should really be unique when used. This is used in the above code because this HTML code is just like that.
:has() is not well supported, I'll keep an eye out.
I mention XPath because the question actually came from my friend and the XPath aspect is exactly what he mentioned, I don't understand that.
After we discussed this issue offline, The conclusion is that it is currently not possible.
Thank you all.
updated: 2022/9/30 Not possible with pure CSS.
The short answer is No, you can't do that.
Pure CSS does not supports this.
After reading the comment, and understanding the op's question, I'm posting a simple solution. And please replace your html id's by class, this is the reason that I'm not using it in my code:
const getSelectorByTagName = (el) => {
const elTagName = el.tagName.toLowerCase();
const els = document.querySelectorAll(elTagName);
for (i=0;i<els.length-1;i++){
if ( el === els[i] ) {
console.log(el, els[i]); // just for you see them
return `${elTagName}:nth-of-type(${i})`;
}
}
return false;
};
const myQuery = document.querySelectorAll('a:has(span)');
/* we know that you want the second one
otherwise we can loop through the array and find it
using textNode, class, etc */
const myEl = myQuery[1]; // the 2ยบ in array
const mySelector = getSelectorByTagName(myEl);
console.log(`The selector is '${mySelector}'`);
console.log(document.querySelector(mySelector));
Ok, the solution works fine! And you got a pure css selector that you need. And now I will explain how to get a parent node using css because this is the question.
If you wish to apply a different style to a parent element is possible using :has pseudo-class, but keep in mind that condition is the child, if the child exists, it changes the parent. At this moment, Edge, Chrome (including Android), Safari (including iOS), Opera and Android Browser support it. Global usage is 84.02%.
How to use it, as a simple example:
Css code:
#supports selector(:has(*)) {
div.parent { width: 100%; height:10px; background: red }
div.parent:has(span.child) { width: 50%; background: green }
}
Html code:
<div class="parent">
<span></span>
</div>
<div class="parent">
<span class="child"></span>
</div>
Js Code:
const elements = document.querySelectorAll('div.parent:has(span.child)');
console.log(elements.length); // output = 1
There is code within "typed" that I am trying to edit and change. Within "typed" there is code that doesn't align with the project.
setTimeout(function() {
document.querySelector('.typed').innerHTML = 'Goodbye World'; // <- this is what changes the content inside the HTML
}, 2000);
<span class="typed">Hello World</span>
Using setTimeout just to add a delay to the change of content to show it works.
Targeting elements by classes is dangerous though in case there is more than 1 element using that class. It would be better to use id instead.
I'm trying to accomplish layout same of google photos and come across to this page https://github.com/xieranmaya/blog/issues/6 . My question is about the final output of his work which can be viewed on this page. https://xieranmaya.github.io/images/cats/cats.html . When you inspect element one of the photos you can see this line
<div ng-repeat="img in imgs" style="flex-grow:70.57291666666667;flex-basis:169.375px;" class="ng-scope">
<img ng-src="stock-photo-34598868.jpg" src="stock-photo-34598868.jpg">
</div>
My Question is what computation did he use to get the value of flex-grow and flex-basis since it's not mentioned on the tutorial?
Here you can see that with jQuery I simulate the flex grow effect as seen in the Angular version.
$('img').each(function() { //Cycle all the images
var img = $(this);
//Apply flex settings
img
.css('flex-grow', img.width() * 100 / img.height())
.css('flex-basis', img.width() * 240 / img.height() + 'px');
});
Fiddle
When i hit Ctrl+F to find words in chrome all the letters with the search text becomes yellow.
Anyone have any idea how it is done? Am just curious to know this!
BTW i'am searching for this is to implement a functionality like this using google extensions. Right now what am doing is finding that particular text and replace it with something like below.
Original text: hello
Replaced text: '<span style="background:yellow;">hello</span>';
Any ideas?
Edit: I think browsers don't allow you to use native higlight
mechanism. But you can imitate this functionality using
Javascript/jQuery.
There are lots of javascript and jQuery plugins to do that. General idea is finding all occurrences of the given word(s) and replacing them with some HTML code. (Which have different background color or larger font size etc.) For find-replace operations, RegEx will be beneficial.
Basic, non-optimized example;
/* Instead of body you can use any container element's selector */
$('body').each(function(){
var allContent = $(this).text();
var wordsToBeHighlighted = ['Hello','World'];
wordsToBeHighlighted = $.map(wordsToBeHighlighted, function(str) {
return preg_quote(str);
});
$(this).html(allContent.replace(new RegExp("(" + wordsToBeHighlighted.join('|') + ")" , 'gi'), "<b style='color: red;'>$1</b>"));
});
function preg_quote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
Source
I want users to know what page they are currently on by highlighting the hyperlink.
I'm not using a list of buttons if that matters (<li>), I'm just using links.
I don't want to have to give each link a class on each page to tell if it's active or not.
Is there anyway of doing this without giving each active link a class?
I've looked into this issue and from what I see jQuery can be a possibility but I'd prefer to use it as I'm not clued up on jQuery. If anyone does know of any jQuery solutions I'll be happy to look at them!
Any automatic active link detectors about? :)
I think this may work but I haven't tested it.
It's using jQuery and it's pretty readable.
You should however process the path name to have just the part needed for the match in the hrefHasPath function.
var links = $("#links a"); // gets all links within something with an id of "links"
var pathname = window.location.pathname; // current url
//for each link see if the href has something in the path, and if it does add a css class
$.each(links, function(){
if(hrefHasPath($(this).attr("href"))){
$(this).addClass("highlight");
}
});
function hrefHasPath(href){
return (href.indexOf("pathname ") != -1);
}
Off the top of my head, I would approach this by grabbing all <a> elements (or ones in a certain grouping, or in a class, like navigation) and checking if the CURRENT URL == a.href
Something like so:
var a = document.getElementsByTagName('a');
for (var idx= 0; idx < a.length; ++idx){
if(a[idx].href == document.URL){
// some styles here to the link background
a[idx].style.backgroundColor = 'red';
}
}
If you add in jQuery it will make your selector easier for styling and the like.