Jquery css dynamic or static html elements

on my website I have to create dynamic elements.

some elements have many properties, such as: id, class, title, href for links, etc.

I looked at some example on different sites, and I saw 2 different ways to create 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 better to use as a coding standard?

+4
source share
1 answer

The second is better, since you do not need to worry about the correct exit from the values. For example, if the values โ€‹โ€‹of different attributes were dynamic and compiled from variables, if you used the first example, you would have to perform string concatenations to format the value, and then if they have some special characters, this can lead to invalid markup.

+1
source

Source: https://habr.com/ru/post/1386926/


All Articles