0

is there is any alternate solution for the below javascript code i need to use JS value as JS variable or function

<script type="text/javascript">
    var count = 1;
    var parent_var = '.parentElement'; //dynamically get variable
    while(count == 5){
      parent_var = parent_var+'.parentElement';
      parent = document.getElementById('html_id')+parent_var;
      console.log(parent); 
      count++;
    }
</script>

EXPECTED OUTPUT

parent = document.getElementById('html_id').parentElement.parentElement.parentElement.parentElement.parentElement;

i need to get parent element dynamically based on some loop count, every loop append .parentElement

it dynamically get before parent in each loop

Thanks in advance ...

2
  • Can you explain what you are trying to do? You say "every loop append" and "each loop" but we don't see any loops. Commented Sep 19, 2017 at 3:41
  • now check ... my question . i hope you understand. Commented Sep 19, 2017 at 3:44

2 Answers 2

1

It seems like you want to get the parent element on each loop. Try doing:

var currentElement = document.getElementById("html_id");
while (currentElement.tagName.toLowerCase() != "body") {
  currentElement = currentElement.parentElement;
  console.log(currentElement);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you :) .. I edited the question and please see expected output.
Do you want to see that thing or what is returned by that? Also, how far back do you want it to iterate? Eventually it well get to the html page and then to null
0

Looks you want to let string to be executable code, you could try eval() function.

parent = eval("document.getElementById('html_id')"+parent_var);

2 Comments

Thank you, I got answer here .. stackoverflow.com/a/46291542/7052574 and have some security issue. kindly refer below link. security.stackexchange.com/a/94021
As the JS saying goes: eval is evil

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.