0

I have a dynamic table here, i'am trying to add css poperty using jquery for small devices. but iam not getting the output, here is my code

  $("#slidetable td:nth-of-type(8):before").css("content:","Credit WP");
kannan D.S
  • 1,107
  • 3
  • 17
  • 44
  • 1
    You can't target pseudo-elements (`:before`, in this case) with JavaScript. Also you can just use [CSS Media Queries](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries) to target specific device sizes. – James Donnelly Oct 10 '14 at 11:17
  • @ james Donnelly but my table is dynamic – kannan D.S Oct 10 '14 at 11:19
  • iam just trying to add pseudo-elements using jquery if ($(window).width() < 500) { $("#slidetable td:nth-of-type(8):before").css("content:","Credit WP"); } – kannan D.S Oct 10 '14 at 11:21
  • You can do this with Media Queries. Please see my answer: http://stackoverflow.com/a/26298211/1317805. – James Donnelly Oct 10 '14 at 11:22
  • if content: "Credit WP"; is dynamic then how it is possible – kannan D.S Oct 10 '14 at 11:26
  • It isn't. The first thing I said was: "You can't target pseudo-elements (`:before`, in this case) with JavaScript.". You'll need to use a different element instead of CSS's generated content. I've updated my answer to reflect this. – James Donnelly Oct 10 '14 at 11:27
  • @kannanD.S For dynamic content, you can use data-* attribute as content, and set it using javascript/jQuery. BTW, you should use window matchMedia property, not window width to target specific viewport. See: https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/ (search for polyfill to support older IE) and http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-using-jquery-e-g-before-and-after – A. Wolff Oct 10 '14 at 11:32

1 Answers1

2

You can't target pseudo-elements (:before, in this case) with JavaScript. Also you can just use CSS Media Queries to target specific device sizes:

A media query consists of a media type and at least one expression that limits the style sheets' scope by using media features, such as width, height, and color.

@media screen and (max-device-width: 460px) {
    #slidetable td:nth-of-type(8):before {
        content: "Credit WP";
    }
}

@ james Donnelly but my table is dynamic – kannan D.S

That doesn't matter. Here is a JSFiddle demo showing how a dynamically-created div element is still affected by CSS: http://jsfiddle.net/gvdt22h2.

if content: "Credit WP"; is dynamic then how it is possible – kannan D.S

In this case you'll need to use a different element instead of CSS's generated content. You could use a span element, for instance:

$("#slidetable td:nth-of-type(8)").append('<span>Credit WP</span>');
James Donnelly
  • 126,410
  • 34
  • 208
  • 218