0

I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.

my code:-

 <div myCondition="1 == 2" id="hey"></a>
 <script>
  var a = document.getElementById('hey');
  var x = a.getAttribute('myCondition');
  if(x){
    console.log('accepted')
  }else{
    console.log('not accepted')
  }
</script>

above program should return not accepted value of myCondition attribute can be very complex for example:-

'hello' == 'hello'
 5>1  etc
3
  • use === instead Commented Jan 2, 2018 at 2:31
  • Why are you storing conditions in attributes rather than in JavaScript / server-side code? Commented Jan 2, 2018 at 2:46
  • 3
    I don't know which one wins the bad practices contest: the question, that mixes presentation with data, or the accepted answer, that uses eval... Commented Jan 2, 2018 at 2:47

1 Answer 1

1

I guess what you need is the eval function. As it says in the provided link:

The eval() function evaluates JavaScript code represented as a string.

So, you can change your code like this:

if( eval(x) ){
  console.log('accepted')
}else{
  console.log('not accepted')
}

P.S: That being said, I don't think doing it like this really safe.

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

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.