I am returning a HTML tag in JavaScript which has values
var code = 'brand':
return `<div class="${code}_label">${code.toUpperCase()}</div>`;
I don't want to use $ and I want to concatenate through + in JavaScript
var code = 'brand':
return `<div class=code+"_label">code.toUpperCase()</div>`;
But this is not giving the expected output.
Can anyone please help?
Thanks in advance
Your quoting is a bit wrong:
function createTag() {
var code = 'brand';
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
}
console.log(createTag());
Another solution using dom api would be:
function createTag() {
var code = 'brand';
var div = document.createElement("div");
div.id = code + '_label';
div.innerText = code.toUpperCase();
return div;
}
console.log(createTag());
Without ES6 you can use single quotes:
var code = 'brand':
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
I think it's the problem with how you use quotes.
var code = 'brand':
return `<div class=` + code + `_label">` + code.toUpperCase() + `</div>`;
You are using wrong quoting.
var code = 'brand';
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
Related
I am trying to create a function that will add buttons with their corresponding event listeners
var wordCount = 0;
function createButton(word, alert){
document.querySelector('body').innerHTML += "<button id=\"word-" + wordCount + "\">" + word + "</button>";
document.querySelector('#word-' + wordCount).addEventListener('click', function(){
console.log(alert);
})
wordCount++;
}
createButton('a', 'A');
createButton('b', 'B');
Only the last button(b) responds. Clicking button(a) does not output anything.
How would you fix this? Are there better ways that I could have implemented this?
I am frequently facing this situation and doing it in a simpler way. see this, (the beauty of the method is if you start the variable full with single quotes, you can add any usual double quoted stuff within it, with ease and without any escaping issues). No addEventListener business needed here. :-)
var full = '';
var wordCount = 0;
function createButton(word, alert) {
alert='\'' + alert + '\'';
full = full + '<a href="javascript:void(0)" onclick="alert(' + alert + ');">'
full = full + '<button id="word-' + wordCount + '" >' + word + '</button>';
full = full + '</a>';
document.querySelector('body').innerHTML += full;
wordCount++;
}
function anyFunction(alert) {
console.log(alert);
}
createButton('a', 'A');
createButton('b', 'B');
In my javascript app, I insert a user message using the code:
var displayMessages = function(response, onBottom) {
var user = GLOBAL_DATA.user;
var acc = '';
for(var i=0; i<response.length; i+=1) {
var obj = response[i];
var acc_temp = "";
acc_temp += '<div class="message ' + (obj['user_id']==user['id'] ? 'message-right' : 'message-left') + '">';
acc_temp += '<div>' + Autolinker.link($(obj['message']).text()) + '</div>';
if (obj['user_id']!=user['id']) {
acc_temp += '<div class="message-details">' + obj['first_name'] + ' ' + obj['last_name'] + '</div>';
}
acc_temp += '<div class="message-details">' + obj['date_sent'] + '</div>';
acc_temp += '</div>';
acc = acc_temp + acc;
}
addMessage(acc, onBottom);
};
The problem is that, if obj['message'] = "<script>alert(1);</script>"; then what gets printed on the screen is "alert(1);" because I use .text(). How can I insert the string with the script tags, so that it looks exactly like that on the page? I don't want it to get executed.
Thanks
I use these helper functions.
function htmlEncode(value){
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}
I would escape the other variables as well if you are not sure that they will not have any executable code.
I solved it using this:
function escapeHTML(str) {
return $("<p></p>").text(str).html();
}
I think you'll need to wrap your object in a dummy tag, then you can retrieve the full html from that.
You'll have issues though, because you're using a script tag, which will be evaluated.
obj['message'] = "<script>alert(1);</script>";
>
$(obj['message']).text();
> "alert(1);"
$(obj['message']).html();
> "alert(1);"
$(obj['message']).wrapAll('<div>').text();
// alerts with 1
> "alert(1);"
Not using a script tag will work.
obj['message'] = "<span>alert(1);</span>";
>
$(obj['message']).wrapAll('<div>').text();
> "<span>alert(1);</span>"
Hit a slight bump on something.
So I have a spreadsheet feed coming through via json.
Once they are loaded, if they contain a certain word, I want an elment that is already on the page to do something.
Having some trouble.
Here is my code:
/*feed*/
function displayContent(json) {
var len = json.feed.entry.length
var divtag = ''
for (var i=0; i<len; i++) {
divtag += [
'<div id=' +' tooltipwrap' + i + '>' +
'<span style="font-size:22px; font-weight:600;">',
json.feed.entry[i].gsx$studentname.$t + ' ' +
'<span class="hide" style="font-size:18px; font-weight:300;">',
json.feed.entry[i].gsx$classlevel.$t
+ '</span>' + '<span id=' + 'tooltipside' + i +'>' +
json.feed.entry[i].gsx$gender.$t + '-' +
'</span>',
'</div>'
].join('');
}
document.getElementById('tipswrap').innerHTML = divtag
}
/* what I wanted to do */
if ($('#tooltipside0').html() === "Senior") {
$("#test1").addClass('no');
}
Here is the JSFiddle
Pay attention to the tabulation. Right now your code is hard to read because you have failed to do so.
Here:
var len = json.feed.entry.length
var divtag = ''
you are missing semi-colons. You have to put semi-colon at the end of any operation, like this:
var len = json.feed.entry.length;
var divtag = '';
Semi-colons serve as operation separators.
Here:
divtag += [
'' +
'',
json.feed.entry[i].gsx$studentname.$t + ' ' +
'',
json.feed.entry[i].gsx$classlevel.$t
+ '' + '' +
json.feed.entry[i].gsx$gender.$t + '-' +
'',
'</div>'
].join('');
You have multiple problems:
You have failed to put your html attributes into quotes, so the resulting html will be invalid. Also, you have used comma instead of plus at the last concatenation.
CONCLUSION: You are obviously not ready to implement this code, because:
- You lack Javascript syntax knowledge
- You lack HTML syntax knowledge
- You do not pay attention to tabulation
As a consequence, your main problem is not what the question states, namely, how to add a class to an element depending on JSON feed. Your main problem is that you lack Javascript and HTML education. Please, follow some tutorials to be able to solve a problem and after that try again to solve your problem. If you fail to do so, then you will have at least an educated guess.
After adding the content to tipswrap add the condition
document.getElementById('tipswrap').innerHTML = divtag; //$('#tipswrap').html(divtag)
if ($.trim($('#tooltipside0').html()) === "Senior") {
$("#test1").addClass('no');
}
Demo: Fiddle
I recommend you add a class to all of your rows called student and then from there use this javascript:
function displayContent(json) {
var len = json.feed.entry.length
var divtag = ''
for (var i = 0; i < len; i++) {
divtag +=
'<div class="student" id="tooltipwrap'+i+'">'+
'<span style="font-size:22px; font-weight:600;">'+
json.feed.entry[i].gsx$studentname.$t +
'<span class="hide" style="font-size:18px; font-weight:300;">'+
json.feed.entry[i].gsx$classlevel.$t +
'</span> '+
'<span id="tooltipside'+i+'">'+
json.feed.entry[i].gsx$gender.$t + '-' +
'</span>'+
'</span>'+
'</div>';
}
document.getElementById('tipswrap').innerHTML = divtag
}
jQuery(document).ready(function($) {
$('.student').each(function() {
if ($(this).text().toLowerCase().indexOf("senior") >= 0)
$(this).addClass('senior');
});
});
Here's a demo
I am getting stuck. Perhaps there is a better way with the regex (like to hear your thoughts).
AS a ONE-OFF the following works if I am just subbing in one thing, say -link-.
var testHtmlStr = '<tr>' +
'<td class="eve"><div class="pad" style="overflow:hidden;">' +
'<img height="50" width="80" title="{%desc%}" alt="{%desc%}" src="{%image%}">' +
'<div class="sum">{%name%}</div>' +
'{%star_rating_html%}' +
'{%eventC%}' +
'<span class="block">{%evenC%}</span>' +
'</div></td>' +
'<td class="mor"><div class="pad"><a class="mor" href="{%link%}">{%linkName%}</a>' +
'</div></td>' +
'</tr>';
var ss = 'link';
var syntax = new RegExp('(^|.|\r|\n)(\{%\s*(' + ss + ')\s*%\})',"gi");
alert(testHtmlStr.replace(syntax, '$1TESTESTESTESTS'));
The following is my code and it DOES NOT WORK. I can't figure out why. Same regex, same html template pattern. Also, my .each reiterates thru the string, but it seems after every reiteration the string returns to its unmodified state. Basically, whatever is the html string like so {%somehashkey%}, I want it to be replaced with the corresponding hash value.
I figured my code would work, can't figure out what is wrong. Something is out of wack, I know that. I can't hunt it down. Your thoughts?
(function($){
var testHTML2 = '<tr>' +
'<td class="eve"><div class="pad" style="overflow:hidden;">' +
'<img height="50" width="80" title="{%desc%}" alt="{%desc%}" src="{%image%}">' +
'<div class="sum">{%name%}</div>' +
'{%rating%}' +
'{%eventC%}' +
'<span class="block">{%evenC%}</span>' +
'</div></td>' +
'<td class="mor"><div class="pad"><a class="mor" href="{%link%}">{%linkName%}</a>' +
'</div></td>' +
'</tr>';
var type = "yahoo";
var disp = {};
disp.eventC = '5';
disp.rating = "<div>rating here</div>";
switch (type) {
case 'yahoo':
disp.link = 'http://www.yahoo.com';
disp.image = 'SOMe IMAGE' ;
disp.name = "VENICE BEACH";
disp.desc = 'MORE INFO ';
disp.linkName = 'YAHOO';
break;
default:
disp.link = 'http://www.google.com';
disp.image = 'Some IMAGE';
disp.name = "BABY BABY";
disp.desc = 'MORE INFO YOYOYO';
disp.linkName = 'GOOGLE';
}
$.each( disp, function(t, num){
var syntax = new RegExp('(^|.|\r|\n)(\{%\s*(' + t + ')\s*%\})',"gi");
testHTML2.replace(syntax, num)
});
alert(testHTML2);
})(jQuery);
You are not assigning new value to testHTML2.
testHTML2 = testHTML2.replace(syntax, num)
I am trying to convert emoticon codes into emoticon images. I want to write it within a function. Here is original code without function yet :
$.get("showMsgLive.php?username=" + str + "&servertime=" + servertime + "&usertime=" + usertime + "&lastmsgID=" + lastmsgid, function(newitems){
newitems = newitems.replace(/\(smile1\)/g, '<img src="images/emoticons/emobasic/smile1.gif" class="emoticon"/>')
.replace(/\(rabbit18\)/g, '<img src="images/emoticons/emospecial/rabbit18.gif" class="emoticon"/>')
.replace(/\(rabbit19\)/g, '<img src="images/emoticons/emobasic/rabbit19.gif" class="emoticon"/>')
.replace(/\(rabbit20\)/g, '<img src="images/emoticons/emoadvance/rabbit20.gif" class="emoticon"/>')
.replace(/\(sheep4\)/g, '<img src="images/emoticons/emospecial/sheep4.gif" class="emoticon"/>'); //end of special emo
newitems.innerHTML = newitems;
api.getContentPane().append(newitems);
});
Here is the code that I try to write it in function :
function convertTextEmo(newitems){
newitems = newitems.replace(/\(smile1\)/g, '<img src="images/emoticons/emobasic/smile1.gif" class="emoticon"/>')
.replace(/\(rabbit19\)/g, '<img src="images/emoticons/emospecial/rabbit19.gif" class="emoticon"/>')
.replace(/\(rabbit20\)/g, '<img src="images/emoticons/emobasic/rabbit20.gif" class="emoticon"/>')
.replace(/\(sheep4\)/g, '<img src="images/emoticons/emoadvance/sheep4.gif" class="emoticon"/>'); //end of special emo
return newitems;
}
jQuery.get("showMsgLive.php?username=" + str + "&servertime=" + servertime + "&usertime=" + usertime + "&lastmsgID=" + lastmsgid, function(newitems){
convertTextEmo(newitems);
api.getContentPane().append(newitems);
});
I didn't put innerHTML in the function because I don't know where and how to put it, and the output didn't success convert the code into image. May I know where or how to put innerHTML in the function and return the value?
newitems.innerHTML = newitems; should not even work as newitems is a string and not an HTML element.
I think all you have to do is:
api.getContentPane().append(convertTextEmo(newitems));
Another tip to improve your code: As the image names of are the same as identifiers in the text, you could just create an array of names:
var emoticons = ['smile1', 'rabbit18',...];
and loop over it:
function convertTextEmo(newitems, icons){
var pattern, content;
for(var i = icons.length; i--; ) {
pattern = new RegExp('\(' + icons[i] + '\)', 'g');
content = '<img src="images/emoticons/emospecial/' + icons[i] + '.gif" class="emoticon"/>';
newitems = newitems.replace(pattern, content);
}
return newitems;
}
jQuery.get("showMsgLive.php?username=" + str + "&servertime=" + servertime + "&usertime=" + usertime + "&lastmsgID=" + lastmsgid, function(newitems){
newitems = convertTextEmo(newitems);
api.getContentPane().append(newitems);
});
Your function returns the modified HTML.