How to get a DOM element's ::before content with JavaScript?
Pass ":before"
as the second parameter to window.getComputedStyle()
:
console.log(getComputedStyle(document.querySelector('p'), ':before').getPropertyValue('content'));
p::before,p::after { content: ' Test ';}
<p>Lorem Ipsum</p>
How do you find coordinates of pseudo elements?
The css property bottom
is not the same as a bounding rectangle's bottom
property. The fact that the top and bottom css values end up being the height of the pseudo element in the first test is just coincidence.
The bounding rectangle bottom
is calculated based on its y position and its height:
https://drafts.fxtf.org/geometry/#dom-domrectreadonly-domrect-bottom
The bottom attribute, on getting, must return max(y coordinate, y
coordinate + height dimension).
The css bottom
property however is a position value. With an absolute
positioned element:
https://www.w3.org/TR/CSS2/visuren.html#propdef-bottom
Like 'top', but specifies how far a box's bottom margin edge is offset
above the bottom of the box's containing block.
So you can't simply use the formula bottom-top
to get the pseudo element's height. You have to take the closest positioned container element's height into account, in your case the blockquote.
So for the blockquote element: Its height is 105px
. The top of the quote is 25px
above the top, and its bottom is 50px
below the bottom. With those values you get the pseudo element's height:
105 - -25 - -50 = 180
As for the coordinates: the x,y properties seem to be browser specific as they do not exist in Firefox, IE, etc. And I cannot find out what they are exactly supposed to hold. Also the ones on the bounding box are simply the left,top values.
So if you want to calculate the left, top values you would have to use its left, top values and take again into account the closest positioned parent's location
var rect = e.getClientRects();
var pseudoStyle = window.getComputedStyle(e, ':before');
//find the elements location in the page
//taking into account page scrolling
var top = rect.top + win.pageYOffset - document.documentElement.clientTop;
var left = rect.left + win.pageXOffset - document.documentElement.clientLeft;
//modify those with the pseudo element's to get its location
top += parseInt(pseudoStyle.top,10);
left += parseInt(pseudoStyle.left,10);
How to get pseudo elements in WebdriverIO+Appium
Thanks to Jeremy Schneider (@YmerejRedienhcs) & Erwin Heitzman (@erwinheitzman) for help!
One solution is to use the execute
function:
let contentMode = browser.execute(() => {
let style = document.defaultView.getComputedStyle(document.querySelector('body'),'::before');
return style.getPropertyValue('content')
});
Alternatively maybe something could also be done with getHTML
.
Retrieve a pseudo element's content property value using JavaScript
According to MDN, the second parameter to the .getComputedStyle()
method is the pseudo element:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt (Optional) - A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
Therefore you could use the following in order to get the pseudo element's content
value:
window.getComputedStyle(this, ':before').content;
Updated Example
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
If you want to get the entity code based on the character, you can also use the following:
function getEntityFromCharacter(character) { var hexCode = character.replace(/['"]/g, '').charCodeAt(0).toString(16).toUpperCase(); while (hexCode.length < 4) { hexCode = '0' + hexCode; }
return '\\' + hexCode + ';';}$('.coin').each(function() { var content = window.getComputedStyle(this, ':before').content; $('input', this).val(getEntityFromCharacter(content));});
.dollar:before { content: '\0024'}.yen:before { content: '\00A5'}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="coin dollar"> <input type="text" /></div><div class="coin yen"> <input type="text" /></div>
Use of Pseudo-Element ::before in JavaScript
No, you cannot access :before
or :after
from javascript, because they are not a part of the DOM. However you can still achieve your goal by using CSS classes. Example:
<script>
document.getElementById('abc').className += "minus";
</script>
<style>
#all-address:before {
display: none;
}
#all-address.minus:before {
display: block;
}
</style>
Get the actual text-content of pseudo-element content using pure javascript
Since you are saying you already got the string, but with quotes, then do:
var t = '"hello"'; // here put your text resulting from your prev codeconsole.log(t);
t = t.replace(/"/g, '');console.log(t);
How locate the pseudo-element ::before using Selenium Python
Pseudo Elements
A CSS pseudo-element is used to style specified parts of an element. It can be used to:
- Style the first letter, or line, of an element
- Insert content before, or after, the content of an element
::after
::after
is a pseudo element which allows you to insert content onto a page from CSS (without it needing to be in the HTML). While the end result is not actually in the DOM, it appears on the page as if it is, and would essentially be like this:
CSS:
div::after {
content: "hi";
}
::before
::before
is exactly the same only it inserts the content before any other content in the HTML instead of after. The only reasons to use one over the other are:
- You want the generated content to come before the element content, positionally.
- The
::after
content is also "after" in source-order, so it will position on top of::before
if stacked on top of each other naturally.
Demonstration of extracting properties of pseudo-element
As per the discussion above you can't locate the ::before
element within the DOM Tree but you can always be able to retrieve the contents of the pseudo-elements, i.e. ::before
and ::after
elements. Here's an example:
To demonstrate, we will be extracting the content of ::after
element (snapshot below) within this website:
Code Block:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://meyerweb.com/eric/css/tests/pseudos-inspector-test.html')
script = "return window.getComputedStyle(document.querySelector('body>p.el'),':after').getPropertyValue('content')"
print(driver.execute_script(script).strip())Console Output:
" (fin.)"
This console output exactly matches the value of the content
property of the ::after
element as seen in the HTML DOM:
This usecase
To extract the value of the content property of the ::before
element you can use the following solution:
script = "return window.getComputedStyle(document.querySelector('div.crow'),':before').getPropertyValue('content')"
print(driver.execute_script(script).strip())
Outro
A couple of relevant documentations:
- Document.querySelector()
- Window.getComputedStyle()
Related Topics
Where Should I Put ≪Script≫ Tags in HTML Markup
Include Another HTML File in a HTML File
Jquery Mobile: Document Ready Vs. Page Events
Why Is Using Onclick() in HTML a Bad Practice
How to Check Whether a Checkbox Is Checked in Jquery
JavaScript Code to Stop Form Submission
Retrieve the Position (X,Y) of an HTML Element
Why Isn't My JavaScript Working in Jsfiddle
Difference Between Properties and Attributes in Html
Get the Size of the Screen, Current Web Page and Browser Window
In JavaScript How to Make a "Click" Event Fire Programmatically For a File Input Element
Best Practice: Access Form Elements by HTML Id or Name Attribute
Can JavaScript Read the Source of Any Web Page
Capture Key Press (Or Keydown) Event on Div Element
Calling a JavaScript Function in Another Js File
Do You Need Text/JavaScript Specified in Your ≪Script≫ Tags