-1

EDIT: This question is not a duplicate, I am aware that at this point foo has not been inserted into the DOM. My question is whether or not is is possible to access the elements declared in the string assigned to foo without inserting it into the document object.

In the following code, we declare an HTML element as a JavaScript variable.

<script>
var foo = "<td id = 'bar'>";
</script>

Now, after the <script> tag but before the </script> tag, how do I access the value of id in the table cell?

Eg. calling console.log(foo.id) obviously prints undefined. how could I call the console.log() function (or any other function to access the value of id) to give us the correct value, "bar"?

Im using <td> as an example but I assume this applies to any html tag declared with JS.

4
  • it is not a DOM element until you actually put it in the DOM. The way you have it written it is just a string. Commented Aug 8, 2017 at 0:43
  • @Chase I actually made a mistake in the code I wrote. Updated with explanation. I am aware that it is not a DOM element at this point, I'm just trying to figure out if there is a way to access the id element from the JS variable itself. Commented Aug 8, 2017 at 0:57
  • Since it's not a DOM element at this point and it's just a string, the only thing you can do is parse the string using string functions. Commented Aug 8, 2017 at 13:30
  • @raphael75 that is not entirely true (see my answer below), however since it's not a valid HTML string, the options are limited. Commented Aug 8, 2017 at 14:30

1 Answer 1

0

In your case you'd get what's between the first and second ', which coincidentally happens to be the id by doing:

foo.split("'")[1] // -> bar

However that is not too useful or reusable. You could push an element to memory and set the innerHTML of that node to your string, however the string in your example is not valid HTML, so it would not work.

var temp = document.createElement('html')
temp.innerHTML = str
temp.getElementsByTagName('td')[0].id // -> bar

Can't imagine your use case though, so maybe none are perfect.

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

1 Comment

That's more or less what I figured. Thanks!

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.