How to CSS: Select Element Based on Inner HTML

How to CSS: select element based on inner HTML

This is not possible using CSS. You can, however, do it using jQuery. There's a nice blog post on it you can read.

How to grab a Child by its innerHTML value using CSS Selector?

if you can use jQuery,you can use contains selector:

$(("ul.ui-autocomplete-list > li:contains('mary')"))

for native javascript, this works:

var mary = [].slice.call(document.querySelectorAll("ul.ui-autocomplete-list > li.visible")).filter(function (item){
return item.innerText.includes("mary");
})[0];

Beautifulsoup select an element based on the innerHTML with Python

It's working

import requests
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/questions"
response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

title = [x.get_text(strip=True) for x in soup.select('[class="s-post-summary--content-title"] > a')]
print(title)
votes = [x.get_text(strip=True) for x in soup.select('div[class="s-post-summary--stats-item s-post-summary--stats-item__emphasized"] > span:nth-child(1)')]
print(votes)

Output:

['React Native - expo/vector-icons typescript type definition for icon name', 'React 25+5 Clock is working but fails all tests', 'Add weekly tasks, monthly tasks in google spreadsheet', 'Count number of change in values in Pandas column', "React-Select: How do I update the selected option dropdown's defaultValue on selected value onChange?", 'Block execution over a variable (TTS Use-Case), other than log statements (spooky)', "'npm install firebase' hangs in wsl. runs fine in windows", 'Kubernetes Dns service sometimes not working', 'Neo4j similarity of single node with entire graph', 'What is this error message? ORA-00932: inconsistent datatypes: expected DATE got NUMBER', 'Why getChildrenQueryBuilder of NestedTreeRepository say Too few parameters: the query defines 2 parameters but you only bound 0', 'Is is a security issue that Paypal uses dynamic certificate to verify webhook notification?', 'MessageBox to autoclose after 
a function done', 'Can someone clearly explain how this function is working?', 'Free open-sourced tools for obfuscating iOS app?', "GitHub page is not showing background image, FF console
shows couldn't load images", 'Is possible to build a MLP model with the tidymodels framework?', 'How do I embed an interactive Tableau visual into an R Markdown script/notebook on Kaggle?', 'Dimensionality reduction methods for data including categorical variables', 'Reaching localhost api from hosted static site', 'Finding the zeros of a two term exponential function with
python', 'optimizing synapse delta lake table not reducing the number of files', '(GAS) Email
Spreadsheet range based on date input in the cell', 'EXCEL Formula to find and copy cell based on criteria', 'how to write function reduce_dimensionality?', 'Semi-Radial type Volume Slider in WPF C#', 'tippy.js tool tips stop working after "window.reload()"', 'is there some slice indices must be integers on FFT opencv python? because i think my coding is correct', 'NoParameterFoundException', 'How to get the two Input control elements look exactly same in terms of background and border?', 'My code is wrong because it requests more data than necessary, how can i solve it?', 'Express Session Not Saving', 'Which value should I search for when changing the date by dragging in FullCalendar?', 'Non-constant expression specified where only constant
expressions are allowed', 'Cocoapods not updating even after latest version is installed', 'Ruby "Each with Index" starting at 1?', 'Converting images to Pytorch tensors loses label data', 'itemview in Adapter for recyclerview not getting id from xml', 'Use Margin Auto & Flex to Align Text', '(C++) URLDownloadToFile Function corrupting downloaded EXE', 'Search plugin for Woocommerce website (Free)', 'Create new folder when save image in Python Plotly', "What's the difference between avfilter_graph_parse_ptr() and avfilter_link()?", 'Inputs to toString (java) on a resultset from MySQL', 'Which language i learn in This time for better future? python or javaScript?', 'Hi everyone. I want to write a function in python for attached data frame. I can not figure out how can I do it', 'is there a way in R to mutate a cumulative subtraction to update the same mutated var?', 'making a simple reccommendation system in JavaScript', 'Amchart4 cursor does not match mouse position in screen with zoom', 'Bash curl command works in terminal, but not with Python os.system()']
['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '-2', '0', '1', '0', '0', '0']

Is there a way to change an elements css based off of its inner text?

yeah you can use JavaScript with if and else statement as if condition satisfies. it will be executed to change inner HTML. Give me 2 mins to attach code. I can only do this by using js. Further properties can be introduce as here first the color was nothing but after that I introduced pink color as background.

x = document.getElementById('text')
y = x.innerHTML


if (y=="her") {
x.innerHTML = "Paragraph changed!";
document.getElementById("p2").style.backgroundColor = "pink";
}else{
console.log('lol')
}
#p2{
width:200px;
height:100px;
padding-left: 10px;
}
<div class="p2" id="p2">
<h1 id='text'>her</h1>
</div>

CSS inner-html technique?

With pure CSS, that’s impossible.

Is there a CSS selector for elements containing certain text?

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.

Selecting Elements By InnerHTML with querySelector

I used jq "contains" to achieve this. for example if i want to get anchor tag with some inner Html then i would do something like this

 $('a:contains("sometext")')

How to read the html tags innerHTML value using css selector or xpath.?

This XPath expression

string(/li/span[@id='lastPrice'])

With this well-formed XML

<li class="active">
<span id="lastPrice">1,603.35</span>
<span id="CAToday"></span><br/>
<span class="up" id="change">28.80</span>
</li>

Result

1,603.35

Check in http://www.utilities-online.info/xpath/?save=07d6e884-4f7e-46cc-9aaf-904e6a440f50-xpath

Select inner HTML item in CSS

I believe you cannot do this with only CSS if it is not possible to use an Id or unique class. In this case I think jQuery is the way to go:

$("li").children().eq( $("li").children().length - 1 ).
css('border', '1px solid red');

The idea is to use eq() to pinpoint the deepest child.

Hope this helps



Related Topics



Leave a reply



Submit