Как получить before элемента js

от admin

Get Pseudo elements using Javascript

CSS pseudo-elements are incredibly useful — they allow us to perform a number of other simple tasks while preventing the need for additional HTML elements. To this point, these pseudo-element CSS properties have been unreachable by JavaScript but now there’s a method for getting them!

Assume your CSS looks like:

To retrieve the color property of the .element:before , you could use the following JavaScript:

Passing the pseudo-element as the second argument to window.getComputedStyle allows access to said pseudo-element styles! Keep this snippet in your toolbox for years to come — pseudo-elements will only grow more useful with broader browser support!

Now, for people like me, who mandates to put up a unit test for everything. I’ve been using Protractor for a while and it is AWESOME!. I can do fun stuff like check for the Pseudo elements for ::after and ::before CSS properties.

You can use something like this to execute a script in the browser and grab the values from the element and later assert them against the value of your choice. For instance you would like to check color property of a span class with pseudo element ::after, you can do something like this:

Not to be picky here, but make sure you do convert the rgba to it’s corresponding HEX value when cross-checking.

How do I get reference to the ::before or ::after node in JS?

As far as I know, standard JavaScript has no way to get at the ::before or ::after pseudo-elements. Element.children doesn’t let you get to it.

I know there has to be a way, at least in Chrome-privileged Firefox add-on code, since it lists every ::before element in the page (and apparently getComputedStyle() works on it too, as you can list all styles of it in inspector, which is written in JavaScript).

Where is this API documented, and is it something that’s different and privileged-only in say Firefox and Chrome browser, or something that is on track to be standard soon?

3 Answers 3

The CSS generated content is not part of the DOM, and you wouldn’t be able to do much with the ::before / ::after pseudo-elements, even if you get at them. The only use-cases I can think of are:

Access the CSS computed values on the pseudo-elements. window.getComputedStyle() supports this via an optional 2nd parameter.

Enumerate the generated content. You can accomplish this:

    by using a browser-specific API. In Firefox, the DevTools inspector uses a special interface — inIDeepTreeWalker.

or by walking the DOM and checking (for each element) if it has content in its computed style for :before / :after . For example:

Get the «live» value of a counter defined in CSS, like in How to access CSS generated content with JavaScript — see that question for details.

At least to me, your question is unclear as to exactly what you are attempting to do, or get.

The most direct equivalent to ::before and ::after :

If you are wanting to actually insert content, which is what the ::before and ::after CSS selectors do, then the most direct equivalent is Element.insertAdjacentHTML(position, text) . In that case:

The equivalent of ::before would be:

The equivalent of ::after would be:

Element.insertAdjacentHTML() also has options of afterbegin and beforeend which insert the HTML text just after the beginning, or just before the end, of the referenced Element.

Alternately:

You could insert nodes using Node.insertBefore(newNode, referenceNode) .
For ::before it would be (insert newNode before myNode):

For ::after it would be (insert newNode after myNode):

Obtaining references:

If you are attempting to get a reference to the element that is earlier in the DOM, then it sounds like you are looking for Node.previousSibling . If you are looking for a reference to the element that is later in the DOM, then you are looking for Node.nextSibling .

In DOM walk order:

It is also possible that you are looking for the elements that are just before and just after the reference Node in DOM walk order. However, that is not really what the CSS selectors ::before and ::after do. However, from your mention of Page Inspector, it kind of sounds like this is what you want. If so, then you will can use a TreeWalker to walk the DOM tree.

The following should do what you want (Note: Currently untested, so might be missing something.):

As mentioned by Nickolay, if you want the full detail that Page Inspector, or the DOM Inspector (documentation), provides then you will need to use an inIDeepTreeWalker. However, it is unlikely that you want, or need, the detail which using that Firefox specific non-standard interface provides. You only need it if you want to walk through how something like how an XUL <toolbarbutton> is constructed (not the attributes/properties, but the XBL which makes up a XUL elements like a <toolbarbutton> ). For the vast majority of what you are potentially thinking about, a standard TreeWalker should be just fine.

Читать:
Net err connection refused что за ошибка

With the exception of inIDeepTreeWalker , all of the above are standard parts of JavaScript and do not require elevated privileges (i.e do not require it to be in an add-on).

How to Get Content of ::before Pseudo-Element Using JavaScript?

Find out how to get content value of ::before pseudo-element in JavaScript

  • Daniyal Hamid
  • 30 Sep, 2021
  • 1 min read

In JavaScript, to get the content property value, as specified by ::before pseudo-element, you can use the window.getComputedStyle() method. It exposes the CSSStyleDeclaration object (as read-only), from which you can access the style information of ::before pseudo-element.

For example, you can add » # » before all local links like so:

You can retrieve the content property value (added via ::before ), like so:

If the content property is not defined, then its computed value » none » is returned.

Hope you found this post useful. It was published 30 Sep, 2021 . Please show your love and support by sharing this post.

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using JavaScript (EASY WAY)

So this title you are looking at — Yes its an actual stackoverflow question.The question has 980 upvotes and it’s top answer has 723 upvotes. Then the question arises, why write an article about it then. Well, for starters I really wanted to answer this question, but since I didnt have enough «reputations»,this article is my way of letting people know of this new easy method.

First things first

Scenerio 1:
Imagine you want to grab an element using JavaScript and change its color using JavaScript. Its pretty easy, here we go:

Exit fullscreen mode

Scenerio 2:
This time we create a :before pseudo element on the #text element and then try to change the pseudo element’s background color. So lets see what happens here:

  • Create a basic pseudo element with the styling(if you are new to creating a pseudo element, I suggest you learn that first and come back here):

Exit fullscreen mode

Alt Text

  • Now just a little twist to this, instead of using black as the background color, we are gonna create a :root element in our CSS file inside which we will create a variable ‘—pseudo-backgroundcolor’ with a value of ‘red’ and use this varible as the value for ‘background’ as shown below.

Exit fullscreen mode

Alt Text

  • So by now I hope you are getting some hint of where I am heading. No ? Okay, let me explain. Our goal is simple, we should create a global background color variable and with the help of JavaScript we will grab the root value of the variable and update it using JavaScript so that the effect will be applied to the pseudo elements background color style automatically.

Lets get to work:

Exit fullscreen mode

Alt Text

So as you can see, we grabbed the —pseudo-backgroundcolor varible and used setProperty function to first select the variable and then set its color value from red to green. This is pretty much the code we need.So now if we ever need to change the color, you can just do this dynamically.An example would be to create a button and on click of that button, you can loop through an array of different colors and apply it to this varible.

In the stackoverflow answer, you can see other right ways too, but they just seemed a bit long, while this one just needs you to set the root variable and just write some JS code.

BONUS PART:

Suppose you want to add a text to a pseudo element — we usually add text using the content = «» property.So instead of «» , just create a root variable like we did above and manipulate it using one line of JavaScript.Here’s the code:

Exit fullscreen mode

So thats it, Hope you learned something new today or even saved time finding this solution. I got to find this solution while I was making my app — PrettyCover — which you can use to create Beautiful Cover Images for your blogs.In fact, I have made this cover image using PrettyCover. I would appreciate if you could go and try it out, and if you like it, don’t forget to ⭐ the repo.

Also, here is the codePen containing the full example codes: https://codepen.io/ridzman/pen/poEgPGq?editors=0011

And as always ending the article with a Gif. Please do let me know if there are any corrections or clarifications to be made. Ciao !

Похожие статьи