Hello, all,
I’m trying to use jQuery “appendTo” to dynamically create new form elements, and I’m a bit confused about something.
I’m using the following:
$('<a />').attr('href','javascript:void(0);').addClass('removeLink').html('-remove-').appendTo('<div />').css({'display':'block','text-align':'right'}).appendTo('#wrapperDiv');
… expecting the following…
<div id="wrapperDiv"><div style='display:block; text-align:right'><a href='javascript:void(0);' class='removeLink'>-remove-</a></div></div>
… but the inner DIV is not making it to the DOM…
<div id="wrapperDiv"><a href='javascript:void(0);' class='removeLink'>-remove-</a></div>
Can you not use two or more appendTo()
to get this done?
V/r,
Hi Wolfshade,
You could do:
$('<div />', {
css: {
'display':'block',
'text-align':'right'
},
html: $('<a />', {
href: 'javascript:void(0);',
class: 'removeLink',
text: '-remove-'
})
})
.appendTo('#wrapperDiv');
Which would give you:
<div id="wrapperDiv">
<div style="display: block; text-align: right;">
<a href="javascript:void(0);" class="removeLink">-remove-</a>
</div>
</div>
1 Like
James_Hibbard:
You could do:
Is there any reason you couldn’t do it in one go as a string?
e.g.
var newElement="";
newElement += "<div style='display:block; text-align:right'><a href='javascript:void(0);' class='removeLink'>-remove-<\/a><\/div><\/div>";
$(newElement).appendTo('#wrapperDiv')
1 Like
Although that will work, it’s not as readable in my opinion.
FWIW, I would probably also remove the javascript:void(0);
and inline CSS.
The inline CSS can eventually be moved to a stylesheet - I use inline in the beginning just because it’s easier.
The javascript:void(0);
is used because (at least in older browsers) the hashtag #
will reload the page, and I don’t like leaving the href
attribute blank. (I can be a bit OCD about certain things.)
Both suggestions are top notch. Thank you! I’ll give @James_Hibbard ’s a shot and report back.
V/r,
You can solve that by preventing the default action when the link is clicked:
.myLink{
display: block;
text-align: right;
}
$('<div />', {
class: 'myLink',
html: $('<a />', {
href: '#',
class: 'removeLink',
text: '-remove-',
click: function(e){ e.preventDefault(); }
})
})
.appendTo('#wrapperDiv');
1 Like
or you can omit the href attribute altogether and use CSS to make it look like a (standard) link.
or even use a button element instead, since the link doesn’t refer to a resource anyways.
1 Like
Thanks, @Pullo , this worked like a charm! I did take your advice on putting the href
in the jQuery, but still am not using #
, as even with e.preventDefault()
, it was still reloading the page in FireFox. I had to tweak it, a bit, to get it to work with something else, but you have saved me a ton of time.
V/r,
system
Closed
October 9, 2015, 2:01am
10
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.