Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a DOM element's ::before content with JavaScript?

Tags:

I want to know whether it is possible to get a DOM element's ::before content, which was set by CSS3.

I have tried some ways, but I still can't make it, so it's very confusing to me!

// https://rollbar.com/docs/  const links = document.querySelectorAll(`ul.image-list a`);  links[0]; // <a href="/docs/notifier/rollbar-gem/" class="ruby">::before Ruby</a>  links[0]; //  links[0].textContent; //"Ruby"  links[0].innerText; // "Ruby"  links[0].innerHTML; // "Ruby"  // ??? links[0]::before; 

This is the case:

![enter image description here

like image 423
xgqfrms Avatar asked Jun 03 '17 08:06

xgqfrms


People also ask

What is :: before in DOM?

The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.

How can we get elements from the DOM in JavaScript?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

How do I use before in JavaScript?

before() The Element. before() method inserts a set of Node or string objects in the children list of this Element 's parent, just before this Element . String objects are inserted as equivalent Text nodes.

How do I target a pseudo element in JavaScript?

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add a specific class to the parent element and control its pseudo elements in CSS.


1 Answers

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>
like image 92
Patrick Roberts Avatar answered Oct 14 '22 22:10

Patrick Roberts