JavaScript How to get the text content of a ::before pseudo-element? [duplicate] css text content before,css add text before content,content

I generate the numbering of my headers and figures with CSS's counter and content properties:

img.figure:after {
  counter-increment: figure;
  content: "Fig. " counter(section) "." counter(figure);
}

This (appropriate browser assumed) gives a nice labelling "Fig. 1.1", "Fig. 1.2" and so on following any image.

Question: How can I access this from Javascript? The question is twofold in that I'd like to access either the current value of a certain counter (at a certain DOM node) or the value of the CSS generated content (at a certain DOM node) or, obviously, both information.

Background: I'd like to append to links back-referencing to figures the appropriate number, like this:

<a target='_blank' href="#fig1">see here</h>
------------------------^ " (Fig 1.1)" inserted via JS

As far as I can see, it boils down to this problem: I could access content or counter-increment via getComputedStyle:

var fig_content = window.getComputedStyle(
                    document.getElementById('fig-a'),
                    ':after').content;

However, this is not the live value, but the one declared in the stylesheet. I cannot find any interface to access the real live value. In the case of the counter, there isn't even a real CSS property to query.

Edit: Digging deeper and deeper through the DOM specs, I found the DOM Level 2 Style Counter interface. This seems to a) allow access to the current counter value and b) be implemented in Firefox, at least. However, I have no idea on how to use it. My current approach died tragically after this Firebug output:

// should return a DOM 2 Counter interface implementation...
window.getComputedStyle(fig_a_element, ':after')
      .getPropertyCSSValue("counter-increment")[0]
      .getCounterValue();

[Exception... "Modifications are not allowed for this document" code: "7"
 nsresult: "0x80530007 (NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR)"
 location: "http://localhost/countertest.html Line: 71"]

Any idea, how this could be brought to life would be highly appreciated.

Edit 2: Apparently I misinterpreted the Counter object of DOM Level 2 Style. It, too, has no property to return the current counter value. This makes the above approach invalid.

New approach: Is there a possibility to read the content of a pseudo-element via the DOM? That is, can I select the pseudo-element (treeWalker comes to mind) and then get its nodeValue? (If you start to type 'jQuery' now, please reconsider to change that term into 'Sizzle'...)

Answer:1

I cannot find any interface to access the real live value. [of the counter]

Yeah. I don't think there is one. Sorry.

The only thing I can think of would be to go through every element (including its :before/:after pseudo-elements) before the element in the document, looking for counters and adding up how many there are.

Obviously that's hideous. If you're going to try to reproduce the browser's own counter mechanism it would probably be easier (and much more compatible, given IE<=7's lack of counter/content support) to just replace it with your own script-based counters. eg. something along the lines of:

<a target='_blank' href="#prettypicture">this</a>

<div class="counter level=0">...</div>
<img id="prettypicture" class="counter level=1" alt="ooo, pretty"/>
window.onload= function() {
    var counters= Node_getElementsByClassName(document.body, 'counter');
    var indices= [];
    for (var counteri= 0; counteri<counters.length; counteri++) {
        var counter= counters[counteri];

        var level= Element_getClassArgument(counter, 'level');
        while (indices.length<=level)
            indices.push(0);
        indices[level]++;
        indices= indices.slice(level+1);
        var text= document.createTextNode('Figure '+indices.join('.'));
        counter.parentNode.insertBefore(text, counter.nextSibling);

        if (counter.id!=='') {
            for (var linki= document.links.length; linki-->0;) {
                var link= document.links[i];
                if (
                    link.hostname===location.hostname && link.pathname===location.pathname &&
                    link.search===location.search && link.hash==='#'+counter.id
                ) {
                    var text= document.createTextNode('('+indices.join('.')+')');
                    link.parentNode.insertBefore(text, link.nextSibling);
                }
            }
        }
    }
};
Answer:2

read this:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).


Content specified in a stylesheet does not become part of the DOM.

so for this reason the getComputedStyle will not work in this case; i think the only way, is to perform a classic loop through as someone has described below!

Answer:3

I would port your css to Javascript, this enables you to get the figure caption and also you get greater browser coverage. Using jQuery you'd do something like this:

$(function() {
  var section = 0;
  $(".section").each(function() {
    section++;
    var figure = 0;
    $(this).find("img.figure").each(function() {
      figure++;
      var s = "Fig. " + section + "." + figure;
      $(this).attr({alt:s}).after(s);
    });
  });
});

Then you could do:

<div class="section">blabla <img id="foo" src="http://www.example.com/foo.jpg"></div>
<p>Lorem ipsum dolor sit amet <a target='_blank' href="#foo" class="figurereference">see here</a></p>

<script type="text/javascript">
  $(function() {
    $("a.figurereference").each(function() {
      var selector = $(this).attr("href");
      var $img = $(selector);
      var s = $(this).text() + " (" + $img.attr("alt") + ")";
      $(this).text(s);
    });
  });
</script>

Though I agree that doing this using CSS would be very neat.

Answer:4

I have the following scenario: <body class="theme-blue nav-black"> <a href="#" data-class="theme-blue">Blue theme </a> <a href="#" data-class="nav-black">Dark Nav</a>...

I have the following scenario: <body class="theme-blue nav-black"> <a href="#" data-class="theme-blue">Blue theme </a> <a href="#" data-class="nav-black">Dark Nav</a>...

  1. extract match from regex
  2. extract match from regex python
  3. extract match in python

I'm stuck in the situation where my child component (autocomplete) needs to update a value of its parent (Curve), And the parent needs to update the one of the child (or to completely re-render when a ...

I'm stuck in the situation where my child component (autocomplete) needs to update a value of its parent (Curve), And the parent needs to update the one of the child (or to completely re-render when a ...

I have written following jQuery for calculating age when user selects date from date picker and the focus of textbox(#dobfield) is lost then the calculated age should get displayed on textbox (#age). ...

I have written following jQuery for calculating age when user selects date from date picker and the focus of textbox(#dobfield) is lost then the calculated age should get displayed on textbox (#age). ...

  1. display selected date in datepicker
  2. display selected date from calendar into textbox
  3. display selected date in textbox in asp.net
  4. display selected date in jquery
  5. power bi display selected date range
  6. jquery datepicker display selected date
  7. show selected date in datepicker
  8. how to show selected date in datepicker
  9. selected date in jquery datepicker
  10. selected date in datepicker

I am trying do cache busting using webpack by adding a hash to the end of each javascript file. My webpack configuration file is below: const AssetsPlugin = require('assets-webpack-plugin'); const ...

I am trying do cache busting using webpack by adding a hash to the end of each javascript file. My webpack configuration file is below: const AssetsPlugin = require('assets-webpack-plugin'); const ...

  1. webpack cache busting index.html
  2. webpack cache busting css
  3. webpack cache busting images
  4. webpack cache busting
  5. webpack cache busting js
  6. cache busting webpack
  7. webpack 4 cache busting
  8. react webpack cache busting
  9. webpack bundle cache busting
  10. webpack chunk cache busting
  11. angular webpack cache busting
  12. laravel webpack cache busting
  13. webpack disable cache busting
  14. vue webpack cache busting
  15. webpack html cache busting
  16. webpack 2 cache busting
  17. wordpress webpack cache busting
  18. webpack dynamic import cache busting
  19. angular cli webpack cache busting
  20. html-webpack-plugin cache busting