1

// Helper func
init = (obj, id) => {
  return obj.style.split(':')[id]
}

train = (i, o) => {
  iProp = init(i, 0);
  iVal = init(i, 1);
  oProp = init(o, 0);
  oVal = init(o, 1);

  alert($(i.dom).css('color'))
}

train({
  dom: 'p',
  style: 'color:rgb(0, 0, 0)'
}, {
  dom: 'p',
  style: 'color:rgb(0, 50, 65)'
})
p {
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text</p>

When I run the code it gives an empty alert, in anWriter Editor it gives an alert 'Undefined'. Why jQuery doesn't see CSS, but I added CSS at the top of the HTML page. Why does it output undefined and how to fix it?

6
  • where is the jQuery code? Commented Jun 22, 2018 at 16:20
  • 5
    CSS stylesheet is not the same as element's style object. Commented Jun 22, 2018 at 16:20
  • @LelioFaieta his alert is doing a jQuery selector and method call Commented Jun 22, 2018 at 16:22
  • @Taplar thanks, didn't notice that :-) Commented Jun 22, 2018 at 16:23
  • Are we missing something here, running your snippet I get rgb(0, 0, 0), this is using Chrome. Commented Jun 22, 2018 at 16:29

2 Answers 2

1

I don't think its problem with jQuery or javascript for below reasons:

  1. I ran your code and found that the alert is being fired way before the DOM is actually rendered. Please see the screenshot below:

The problem output

  1. Your alert is getting called automatically while your script is getting triggered, which is before the HTML being rendered. So, I moved the script to the bottom of the document and it worked. Please see the screenshot below: Expected output

In a nutshell, I would suggest calling the alert manually when your DOM is actually ready.

Hope it will help.

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

Comments

1

Because your DOM wasn't rendered when you call the alert. Try with jquery ready function:

// Helper func
init = (obj, id) => {
  return obj.style.split(':')[id]
}

train = (i, o) => {
  iProp = init(i, 0);
  iVal = init(i, 1);
  oProp = init(o, 0);
  oVal = init(o, 1);
  
  $(function(){
    alert($(i.dom).css('color'));
  });
}

train({
  dom: 'p',
  style: 'color:rgb(0, 0, 0)'
}, {
  dom: 'p',
  style: 'color:rgb(0, 50, 65)'
})
p {
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.