Reputation: 1170
I'm trying to make functions that return me an HTML element as a string so I can eventually append them to the DOM and pass them around my functions. I have paragraph, heading, and div's working but cannot for the life of me seem to get links to work.
This is the non-working codepen
The javascript in question is:
function link(href,text,css){
let target = `<a href="#"></a>`;
if(css == null ){
return target;
}
return addStyles(target,css);
}
My addStyles function is:
function addStyles(target,css){
if(css == null ){
return target;
}
let props = Object.keys(css);
props.forEach((prop)=>{
switch(prop){
case 'id':
$(target).attr('id', css[prop]);
break;
case 'class':
let classes = css[prop];
if(Array.isArray(css[prop])){
classes = css[prop].toString().replace(',', ' ');
}
$(target).addClass(classes);
break;
default:
$(target).attr('data-name', 'Timi');
}
});
return target;
}
which for a long time gave me errors but only when calling it from the link
function. I tried hard-coding in the href to see if maybe my string literals were giving me the errors but still no avail.
while calling it from this function it works perfectly
function createDiv(css){
let newDiv = $(div);
return addStyles(newDiv,css);
}
I say that the addStyles function works and that I think it's the link()
that is giving me problems because createDiv works and appends the DOM with these calls
app.append(createDiv({id: 'testing'}));
app.append(createDiv({class: ['bar', 'snuff']}));
app.append(createDiv()).append(createDiv({class: 'timi'})).append(paragraph('Hey guys!'));
$('#testing').append(heading(1,'Hello'));
Upvotes: 2
Views: 684
Reputation: 1008
The reason your createDiv
function is working as expected and your link
function isn't is because you haven't wrapped your representation of an html element (the one you pass to addStyles
) in a jQuery wrapper like you do in your createDiv
function. See my below code for what I've changed to get it to work:
function link(href,text,css){
let target = `<a href="${href}">${text}</a>`;
if(css == null ){
return target;
}
return addStyles($(target)[0],css);
}
I'm a little lost actually why we need to add [0]
to $(target)
but we do. Maybe someone else could chime in about why that is the case with <a href="${href}">${text}</a>
and not with <div></div>
Edit: disregard above about the [0]
and see comments on this answer.
Upvotes: 0
Reputation: 3758
You forgot to wrap the a tag with bling:
let target = $(`<a href="#"></a>`);
Upvotes: 1
Reputation: 1347
your let target = <a href="#"></a>;
is a string. you should use a DOM and manipulate its attribute instead
function link(href,text,css){
let target = document.createElement('a');
let linkText = document.createTextNode(text);
target.appendChild(linkText);
target.href = href;
if(css == null ){
return target;
}
return addStyles(target,css);
}
Upvotes: 2