0

I am using jQuery to edit html elements using .each on all off a class. If I try to log any of the attributes then I will just get "" even though I have set the attributes to something in my css file.

Why is this happening? Can the javascript file not access the css attributes?

4
  • Post sample code Commented Mar 24, 2017 at 21:10
  • 1
    .css can only access the attributes that are in the style="..." attribute, or were added by .css() dynamically. It doesn't return attributes that are inherited from style sheets. Commented Mar 24, 2017 at 21:14
  • 1
    To get inherited attributes, you have to use the native Javascript getComputedStyle function. Commented Mar 24, 2017 at 21:15
  • Getting computed elements is not so simple. See the question I mentioned above. Commented Mar 24, 2017 at 21:41

1 Answer 1

0

As I'm unclear whether you mean CSS attributes or DOM element attributes, here's an explanation for both:

To loop through some elements before reading their (in this case value) attributes, you can do this like:

$('.element').each(function(){
    console.log( $(this).attr('value') );
});

To loop through some elements before reading their CSS properties, you can do this like:

$('p').each(function(){
    console.log( $(this).css('width') );
});

Take a look at the console to see the three elements width being output: https://jsfiddle.net/nrfxn9nb/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.