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

3

36

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

Davilman answered 3/6, 2017 at 8:42 Comment(1)
getComputedStyle(links[0], '::after').getPropertyValue('content');Davilman
H
41

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>
Helotry answered 3/6, 2017 at 8:51 Comment(0)
N
4

getComputedStyle() & getPropertyValue()

image

getComputedStyle(document.querySelector('span.search-box'), '::after').getPropertyValue('content');

image

Nephro answered 12/9, 2017 at 8:13 Comment(0)
C
0

    document.addEventListener('DOMContentLoaded', function() {
      var widthval = 12;
      var style = document.createElement('style');
      style.innerHTML = '.classname::before {content: " ! "; color: red; width: ' + widthval + 'px !important;}';
      document.head.appendChild(style);
    });
 <div class="classname">
        Main Title
    </div>
Caseycash answered 17/10, 2023 at 4:58 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Starla

© 2022 - 2024 — McMap. All rights reserved.