3

I dont know good method how to get DOM element from template by javascript.

Example template:

<script id = "template" type="text/template">
    <div>text1</div>
    <div>text2</div>
    <div>text3</div>
</script>

For example i want get div with "text2"

There is ways which i know, all of them are bad:

  1. Add "class" to all elements - it breaks semantics (class created for CSS). In big projects you must use very long names for classes, its very inconvenient.

  2. Get element by his number (index) - when adding a new element, you must rewrite old numbers in your code.

1
  • i think you perverting html template's idea Commented Jun 9, 2012 at 8:05

2 Answers 2

1

I see a couple of options:

  1. If you don't want to use class , you can use a data-* attribute.

  2. Assuming you load the template once and then duplicate its contents as desired, you could put id values on the elements in the template, which you then remove when cloning them and adding them to the document (so you don't end up with the same id on more than one copy of the element, which would be invalid and probably counterproductive).

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

Comments

0

Maybe you can also create as many templates as you need. One for each div. If you need to get each div at a time you must set ids to them ... of course you can also browse the dom inside script element to find the one you're interested in ...

Home this helps

Regards

mimiz

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.