4

in my website i have to create dynamic elements.

some elements have lots of properties like: id, class, title, href for links etc...

i was looking at some example on different sites and i saw 2 different way i can build my code

#1 static

$('#mydivid').html('<a href="http://domain.com/page.html" title="my link" id="linkid" class="links-green">link</a>');

#2 dynamic

var anchor = $('<a />', {
  className: 'links-green',
  id: 'linkid',
  title: 'my link',
  href: 'http://domain.com/page.html',
  text: "linkk",
}).appendTo('#mydivid');

i would like to know this:

since the result is the same, which one is consider better to use as a coding standard?

1 Answer 1

1

The second is better since you don't need to worry about properly escaping the values. For example if the values of the different attributes were dynamic and comping from variables, if you used the first example you would have to do string concatenations in order to format the value and then if there are some special characters inside those variables this could produce invalid markup.

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.