Change style inside HTML to all class elements - html

I was wondering couple days ago if its possible to do the following.
Lets say we have a basic HTML code with the following in it:
<p class="someinfo"> basic text </p>
<p class="someinfo"> some other information </p>
And we also have some CSS files that are included in the header of the HTML with basic styling like:
.someinfo{
font-size:32px;
color:red;
}
So here comes my question.
If I edit the HTML and put inside the first Paragraph (style="color:black") like down below it will change the color only for that div element.
By changing the style like this is it somehow possible to make the changes appear to all elements with that class name?
<p style="color:black" class="someinfo"> basic div </p>
<p class="someinfo"> some other information </p>
I hope you understand what I'm asking and apologise if it's a stupid question.
P.S. I am asking this because I have the following situation. There is a website that i don't have the access to any of the files on the server, cannot upload any new files. All i can do is create new pages from a text editor which doesn't recognise < style > and < script > tags. All I want to do is change some css on the navigation and on some other items that are part of every page in the website.

This is what CSS is for :) If you want all elements of a given class name to change to black you could change the CSS style to:
.someinfo{
font-size:32px;
color:black;
}
Doing it inline manually wont work.
If you really want to do it inline you could do so programatically with js:
var someInfoElements = document.getQuerySelectorAll(".someinfo");
for(i = 0; i < someInfoElements.length; i++) {
someInfoElements[i].style.color = "black";
}

Option 1
You could define the first element with a style attribute and use JS to make the rest for you, as long as all elements have the same selector.
const someInfo = document.querySelectorAll('.someinfo');
const style = someInfo[0].getAttribute("style");
someInfo.forEach((s) => s.style = style);
<p style="color:red; font-size:32px" class="someinfo"> basic text </p>
<p class="someinfo"> some other information </p>
Option 2
You could add style attributes to each element.
Here is an example:
const someInfo = document.querySelectorAll('.someinfo');
let style = '';
someInfo.forEach((s) => {
if (typeof s.getAttribute("style") === 'string') {
style += s.getAttribute("style");
if (style.slice(-1) !== ';') {
style += ';';
}
}
});
someInfo.forEach((s) => s.style = style);
<p style="color:red;" class="someinfo"> basic text </p>
<p style="font-size:32px" class="someinfo"> some other information </p>
<p style="color:blue" class="someinfo"> and more information </p>
<p class="someinfo"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, soluta animi, optio repellat eius consectetur! Iure repudiandae, architecto doloremque, dolorum totam consequatur minima placeat recusandae nisi earum dignissimos, illum culpa. </p>
As you see I am using color:red and color:blue. Just like in CSS the last attribute wins. In this case the color of your element with the class someinfo is blue and all other CSS attributes and values will be added.

yes you can, if you want to change all paragraph in the div just put "p" in your css code like this: your both elements will change
p {font-size:32px;color:red;}
instead of
.someinfo{font-size:32px;color:red;}
your code will be like this
<style> p { font-size:32px;color:red;} </style>

Related

get content of spans in a div and display it in a list

I have some spans inside my content, and I'd like to get the content of each of them and display it in a list.
Can anybody help me with this? Thanks.
let container = $("#article-content");
let spans = container.find(".footnote");
let outputP = $("#footnotes");
for (let span of spans) {
let listElem = document.createElement("li");
listElem.textContent = span.html;
outputP.appendChild(listElem);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
Post emensos insuperabilis expeditionis eventus <span class="footnote">footnote 1</span> asperitate nimia cuncta foedabat. propinquitate <span class="footnote">footnote 2</span> enim Excogitatum est super his<span class="footnote">footnote 3</span> adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero
supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
</div>
You could do it like this:
$("#container span").each(function() {
var text = $(this).text();
$("<li>").text(text).appendTo("#footnotes");
});
This will find all span in the element with id container, then it will append a li element with the text of the span inside it.
Demo
$("#container span").each(function() {
var text = $(this).text();
$("<li>").text(text).appendTo("#footnotes");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
Post emensos insuperabilis expeditionis eventus <span class="footnote">footnote 1</span> asperitate nimia cuncta foedabat. propinquitate <span class="footnote">footnote 2</span> enim Excogitatum est super his<span class="footnote">footnote 3</span> adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero
supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
</div>
<ul id="footnotes">
</ul>
Use either jQuery or raw JavaScript, but not both. It's confusing to have some native elements and some jQuery objects in a function, and sometimes it just doesn't work. You really don't need jQuery for something like this anyway. See https://youmightnotneedjquery.com.
The find() function returns only the first element that matches. Also, it's intended to accept a filter function, not a selector string. You want querySelectorAll().
There's no element with ID footnotes in your markup. You need to either include it or create it with JavaScript.
Bonus protip: If you use single quotes for JavaScript and double quotes for HTML (including HTML attributes inside JavaScript) you'll rarely have the need to escape quote characters. The nice thing is that most developers use double quotes for HTML, so you'll be consistent.
const containerEl = document.getElementById('container');
const textEls = containerEl.querySelectorAll('.footnote');
const outputListEl = document.createElement('ul');
textEls.forEach(textEl => {
const listItemEl = document.createElement('li');
listItemEl.textContent = textEl.innerText;
outputListEl.appendChild(listItemEl);
});
containerEl.appendChild(outputListEl);
<div id="container">
Post emensos insuperabilis expeditionis eventus <span class="footnote">footnote 1</span> asperitate nimia cuncta foedabat. propinquitate <span class="footnote">footnote 2</span> enim Excogitatum est super his<span class="footnote">footnote 3</span> adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero
supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
</div>

Align icon in Shiny or CSS to the right

I am trying to align an icon to the right of the text in the tabPanel object in Shiny. The formatted icon appears by default to the left of labels. How do I move to the right?
The following is the screenshot of my Shiny app.
Actually, the desired position of the icon (the orange circle) should be like the following.
I am trying to pass the formatting option fa-pull-right as of what I understand from the documentation (Font Awesome: Bordered + Pulled Icons):
icon = icon("circle", class = "about-icon", lib = "font-awesome", "fa-pull-right")
But this seems to be ignored.
I also try to change the behavior using CSS style in the tags$style. There, I change the color, align up, and make it smaller. I am challenged by the pulling to the right.
.about-icon {color:rgb(255, 150, 0); vertical-align: super;
font-size: xx-small; iconAlign: right}
Alternatively, I am not sure how to pass the fa-pull-right to the CSS style. For instance, the following also does not work.
.about-icon {color:rgb(255, 150, 0); vertical-align: super;
font-size: xx-small; fa-pull-right}
I attach here the full (simplified) code.
library(shiny)
ui <- fluidPage(
tags$head(
tags$style(HTML("h2 {font-family: BentonSans Book; font-size:16px}")),
tags$style(".about-icon {color:rgb(255, 150, 0); vertical-align: super;
font-size: xx-small; fa-pull-right ")
),
titlePanel("my App"),
tabsetPanel(
tabPanel(
"Help",
p("Lorem Ipsum"),
p("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit")
),
tabPanel(
"About",
icon = icon("circle", class = "about-icon", lib = "font-awesome", "fa-pull-right"),
p("Lorem ipsum dolor sit amet, consectetur adipiscing elit,"),
p("sed do eiusmod tempor incididunt ut labore"),
p("et dolore magna aliqua.")
)
)
)
server <- function(input, output, session) {
print("do something")
}
shinyApp(ui = ui, server = server)
The fa-pull-right option is in fact a CSS class. You should put it inside the class parameter of the icon function.
icon = icon("circle", class = "about-icon fa-pull-right", lib = "font-awesome")

Jinja2 html representation in python 3

I am writing a flask powered blog and I want to present my comments saved in XML format to the browser, so I opened the XML file and I read from it.
from xml.etree.ElementTree import parse
def blue():
with open('blogcomment.xml') as file:
doc = parse(file)
return '\n'.join("""
<div class="card">
<span></span>
<div class="content">
<p class="date">%s</p>
<h3></h3>
<p class="desc">%s</p>
</div>
</div>
"""%(item.findtext('date'), item.findtext('body')) for item in doc.iterfind('entries/entry'))
Then I called blue
#sqldb.route('/dbresult')
def dbresult():
f = blue()
return f
#Output:
11/14/2007
in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.
11/18/2007
I got the new cube I ordered. It’s a real pearl.
Which is what I wanted but I want it to be in a particular section of my blog, so I created
<!doctype html>
<html>
<head>
</head>
<body>
{{f}}
</body>
</html>
And changed my route to
#sqldb.route('/dbresult')
def dbresult():
f = blue()
return render_template('dbresult.html', f=f)
when I ran the code It Outputted
<div class="card"> <span></span> <div class="content"> <p class="date">11/14/2007</p> <h3></h3> <p
class="desc">in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.</p> </div> </div> <div
class="card"> <span></span> <div class="content"> <p class="date">11/18/2007</p> <h3></h3> <p
class="desc">Got the new cube I ordered. It’s a real pearl.</p> </div> </div>
on the browser as the browser did not interpret the HTML, is it from Jinja2 or what did I do wrong I need help.
blogcomment.xml
<?xml version="1.0"?>
<blog>
<entries>
<entry>
<date>11/14/2007</date>
<name>Jeff</name>
<body>in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.</body>
</entry>
<entry>
<date>11/18/2007</date>
<name>Petter</name>
<body>Got the new cube I ordered. It’s a real pearl.</body>
</entry>
</entries>
</blog>
Flask's default configuration includes autoescaping for .html templates. Therefore when you put {{ f }} into the template the f variable is treated as an unsafe variable and any 'dangerous' character (e.g. < or >) will be escaped (converted to a HTML entity).
To prevent this behavior you can use the safe template filter, which marks the variable as safe so it will not be escaped:
<!doctype html>
<html>
<head>
</head>
<body>
{{ f | safe }}
</body>
</html>
Make sure that f does not contain any malicious code.
A better approach would be that in your blue method you just prepare the data to render (e.g. make a list of dicts from the data) and then you render the comments in a template file using the built in for control statement.

CSS place elemtent at position of another (NOT parent)

I have an XML file which consists mostly of text. However, there are some element in there containing additional information. Let's call these additional information bits "element". In some paragraphs there is none of these, in some paragraph several. Sometimes there are even right after each other. However, in different paragraphs they are always at different positions.
Here's mock up:
<paragraph>
Qui <element>20</element> corti. num sit <element>10</element><element>5</element> igitu pugis quium. quem er Epiendis nessictilluptiudicaribus? qui ipsarent scit verspitomnesse con eiudicitinec tam ret pari Graeperi diurum eo <element>50</element> nebituratam num aerminxeato nilibus. nostereffer est modulceribus, ficantendus anonea Chraectatur, quemodumquae ut pet sum re vivatotertentu vitra cortem nonemod hunturunclia dolum poraectiatiamas rein eximplatorefut egra vartere
</paragraph>
Now I want to transform this XML file into HTML with XSLT. The problem is: The "additonal elements" should appear nowhere in the text, but at a separate column. Like this:
As you can see, the numbers (bearing my "additional information") appear right at the level where they are in the text: "20", "10" and "5" are at the first line, because in the XML source data they are are referenced after the words "Qui" and "sit", which are in the output both at the first line in the text. "50" is right at the level of "eo" nebituram".
How can I achieve this behaviour with CSS?
It is rather easy to put an anchor element in the HTML at this very same position:
eo <a id="some_id"/> nebituratam
Let's say that the "50" is in a span-element
<span stlye="...">50</span>
However, what do I put in the CSS here? Is there a way to state in CSS to place this span right at the level of the anchor with the id "some_id"?
Of course, the anchor can in no way be the parent of the span element.
Honestly, I'm quite sure that my problem is unsolvable without JavaScript or something, but I'd like to avoid skripts wherever I could.
Try This
p{
padding-left:50px;
position:relative;
}
p span{
position:absolute;
left:10px;
top:45%;
font-size:16px;
font-weight:bold;
}
<p>Qui corti. num sit igitu pugis quium. quem er Epiendis nessictilluptiudicaribus? qui ipsarent scit verspitomnesse
con eiudicitinec tam ret pari Graeperi diurum eo <span>50</span> nebituratam num aerminxeato nilibus. nostereffer est modulceribus,
ficantendus anonea Chraectatur, quemodumquae ut pet sum re vivatotertentu vitra cortem nonemod hunturunclia dolum
poraectiatiamas rein eximplatorefut egra vartere</p>

Selenium IDE Xpath vs Webdriver Xpath

I'm newbie with Test Automation. When I locating element through Firepath with target:
xpath=(//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2)
Firefox founds that element and verify text.
But, when I trying to locate this element with Visual Studio 2012 and Selenium Web driver, I constantly have error: "Unable to locate element: {"method":"xpath","selector":"//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2"}" .
I tried escaping:
//td[#id=\"catProdTd_4723290\"]/div/div[2]/h2
but nothing. When I use isElementPresent method, it founds elements.
Is there some special method or rule that should be use when writing Xpath for WebDriver ?
I defined ISelenium variable, WebDriver... Clicks works, WaitForPageToLoad works, but this can not locate element.
IWebElement we= driver.FindElement(By.XPath("//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2"));
HTML from page:
<td class="productItem" id="catProdTd_4723290"><div class="product-details">
<div class="product-aside"> <img border="0" alt="Fork and Spoon Set" src="/_photos/store/glass-large.jpg" id="catlproduct_4723290">
</div>
<div class="product-main">
<h2 class="product-name">Fork and Spoon Set</h2>
<div class="price"><strong>$17.99</strong></div>
<hr>
<div class="attributes"></div>
<hr>
<div class="product-col-1">
<div class="qty"> Quantity: <strong><input type="text" value="1" name="AddToCart_Amount" class="productTextInput" id="Units_4723290"></strong></div>
<div class="stock">(N/A in-stock)</div>
</div>
<div class="product-col-2">
<input type="submit" onclick="AddToCart(192951,4723290,'',4,'','',true);return false;" value="Buy Now" name="AddToCart_Submit" class="productSubmitInput">
<div class="wish">Add to Wishlist</div>
</div>
<div class="product-description">
<h4>Product Information:</h4>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus
</div>
</div>
<!-- End Main -->
</div>
<!-- End Product Details -->
</td>
I must add that I try to wait during debug and with
Manage().Timeouts().ImplicitlyWait
but nothing. This happens on other places also. I using Firefox for tests
You are running into dynamic attributes.
My first recommendation to you. Switch to CSS.
My second recommendation, instead of boiling down into an entire parent-child hierarchy, why don't you just KISS!
So, lets look at your issue. You are trying to fetch the product name. Easy.. we can use classes here.
css=td.productItem h2.product-name
voila, it was that easy to fetch.. instead of having this huge ugly xpath selector, we've simplified it to a css selector.
So onto the next problem, if we have multiple of td.productItem's on the page, we can use a couple things.
Try,
css=td.productItem:nth-child(1) h2.productName
That will select the first td with class, productItem.
note: you may need to specify the td's parent.. e.g. css=div#container td.productItem:nth-child(1)
More specifics...
The reason your xpath is failing, is because of that catProdTd_4723290 id assigned to the <td> element being generated automatically, rendering that element unselectable. You can work around that, by doing starts with. for example, with css -
css=td[id^='catProdTd']
will select that <td> take note though, that there might be more than 1 element selected.
I suggest using such a method for waiting:
public bool boolWaitForElementIsDisplayed(By locator, int secondsToWait)
{
WebDriverWait Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(secondsToWait));
try
{
var FoundElement = Wait.Until<Boolean>(d =>
{
try
{
return (d.FindElement(locator).Displayed && d.FindElement(locator).Enabled);
}
catch
{
return false;
}
});
}
catch (WebDriverTimeoutException)
{
return false;
}
return true;
}
and then check as follows:
IWebElement h2Element = null;
string xpath = "//td[contains(#class,'productItem')]/div/div[contains(#class,'product-main')]/h2";
if (boolWaitForElementIsDisplayed(By.XPath(xpath), 30))
h2Element = Driver.FindElement(xpath);
So, the problem was that page isn't loaded. Why? Because WebElement.Click() not works. Why Click not working?! I don't know.
I resolved problem with clicks using JavascriptExecutor:
IJavaScriptExecutor executor = (IJavaScriptExecutor)chauffeur;
IWebElement webel1 = chauffeur.FindElement(By.CssSelector("#nav ul:nth-child(1) li:nth-child(2) a[href='/products']"));
Instead of using
webel1.Click();
which not works, I used:
executor.ExecuteScript("arguments[0].click();", webel1);