How to insert html as text using .html() in javascript? - javascript

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>"

Related

How to modularize code while creating HTML elements in JavaScript?

I am writing a piece of code to basically call in the top money earner and the top five money earners in a given data set. While writing the code, I realized that there were a couple of spots where I was rewriting the code, basically copying and pasting it. While that works, I wanted to throw the duplicate portion of the code and call it from a function. However, that is not working and I don't exactly know why. Here is the code that is duplicated:
for (let i = 0; i < len; i++) {
html +=
'<li class="top">' +
'<h2>' +
topSalaries[i][8] +
'</h2>' +
'<h3>' +
topSalaries[i][11] +
'</h3>';
}
container.innerHTML = '<ul id = "topSalaries">' + html + '</ul>';
Here is the function I made to be called. However, when I call it, it's not working as expected, where the information shows up on the webpage. I'm using VS Code and am running this on live server so when I save, the webpage automatically updates.
function createHtmlElements(len, html) {
for (i = 0; i < len; i++) {
html +=
'<li class="top">' +
'<h2>' +
topFiveSalaries[i][8] +
'</h2>' +
'<h3>' +
topFiveSalaries[i][11] +
'</h3>' +
'</li>';
}
return html
}
function getTopSalaries(boston, container) {
const people = boston.data;
const len = 5; // only want top five
let topFiveSalaries = sortPeople(people).slice(0,len);
// create the list elements
html = createHtmlElements(len, html);
container.innerHTML = '<ul id = topSalaries">' + html + '</ul>';
}
For one thing topFiveSalaries is going to be undefined in the function createHtmlElements you've created, you must pass it to the function
Ok. So, Thanks Dave for the help. It looks like I also was missing a piece in that I needed to pass the array into the function as well. This is what I wrote and how I called it.
function getTopSalaries(boston, container) {
const people = boston.data;
const len = 5; // only want top five
var topFiveSalaries = sortPeople(people).slice(0,len);
let html = '';
// create the list elements
html = createHtmlElements(len, html, topFiveSalaries);
container.innerHTML = '<ul id = topSalaries">' + html + '</ul>';
}
function getTopEarner(boston, container){
const people = boston.data;
const len = 1;
let highEarner = sortPeople(people).slice(0,len);
var html = '';
// create the list elements
createHtmlElements(len, html, highEarner);
container.innerHTML = '<ul id = topSalaries">' + html + '</ul>';
}
// sort people by income in descending order
function sortPeople(people) {
people.sort(function(a, b) {
return b[11] - a[11];
})
return people
}
function createHtmlElements(len, html, array) {
for (i = 0; i < len; i++) {
html +=
'<li class="top">' +
'<h2>' +
array[i][8] +
'</h2>' +
'<h3>' +
array[i][11] +
'</h3>' +
'</li>';
}
return html
}

HTML tag in JavaScript

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>';

How do you run a JavaScript function on a specific Wordpress page?

I'm trying to run the following script on a specific Wordpress page, but it's not working. The script does work but when not applied to the specific page. Yes the page id is correct. What did I do wrong? Thanks in advance.
<?php if (is_page('page-id-48857') ):?>
<script>
jQuery(document).ready(function ($) {
$(function () {
var $content = $('#jsonContent');
var data = {
rss_url: 'https://inside.calpoly.edu/feed'
};
$.get('https://api.rss2json.com/v1/api.json', data, function (response) {
if (response.status == 'ok') {
var output = '';
$.each(response.items, function (k, item) {
output += '<div class="post-card category-medium published">';
//output += '<h3 class="date">' + $.format.date(item.pubDate, "dd<br>MMM") + "</h4>";
var tagIndex = item.description.indexOf('<img'); // Find where the img tag starts
var srcIndex = item.description.substring(tagIndex).indexOf('src=') + tagIndex; // Find where the src attribute starts
var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
var srcEnd = item.description.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends
var src = item.description.substring(srcStart, srcEnd); // Extract just the URL
output += '<p class="post-meta">';
//output += '<span class="published">' + item.pubDate + '</span>';
output += '#inside.calpoly.edu</span>';
output += '</p>';
output += '<h2 class="entry-title">' + item.title + '</h2>';
//output += '<div class="post-meta"><span>By ' + item.author + '</span></div>';
var yourString = item.description.replace(/<img[^>]*>/g,""); //replace with your string.
var maxLength = 300 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
output += '<div class="excerpt">'+trimmedString + '</div>';
output += 'Read More';
output += '<a class="entry-featured-image-url" href="'+ item.link + '"><img src="' + src + '"></a>';
output += '</div>';
return k < 1;
});
$content.html(output);
}
});
});
</script>
<?php endif; ?>
You are passing in an invalid ID to the is_page() function.
Based off of your code sample, you should be using an integer for your post ID and not a string and also not the 'page-id' portion.
https://developer.wordpress.org/reference/functions/is_page/
Here's some example usages:
// When any single Page is being displayed.
is_page();
// When Page 42 (ID) is being displayed.
is_page( 42 );
// When the Page with a post_title of "Contact" is being displayed.
is_page( 'Contact' );
// When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( 'about-me' );
In your case you should be using:
<?php if (is_page(48857) ):?>
WordPress' is_page() function requires a "Page ID, title, slug, or array of such.". 'page-id-48857' is the body class, you need to just use is_page( 48857 ) since the actual ID is just 48857.
Also note that you should seriously consider using wp_enqueue_script() instead of coding in a custom script tag. It will save you countless headaches in the future.

JSONP not displaying data in HTML

I am currently experimenting JSONP data using native Javascript. I am trying to get the data to display. How ever i am receiving a syntax error. Unexpected token : As far as i am aware i follow the correct steps into in order gather data. Below is a snippet of my code. Link to JSfiddle
<script src="http://linkToMyJSONDetails"></script>
JS
function (data) {
var showStops = '';
for (var i = 0; i < data.markers.length; i++) {
showStops += '<div class="stops">';
showStops += '<h3>' + data.markers[i].smsCode + '</h3>';
showStops += '<h1>' + data.markers[i].name + '</h1>';
showStops += '</div>';
}
document.getElementById('bus-stops').innerHTML = showStops;
}
You need to do 2 things.
First: Add a callback: (Scroll to the right, since your link is a bit long)
http://digitaslbi-id-test.herokuapp.com/bus-stops?northEast=51.52783450,-0.04076115&southWest=51.51560467,-0.10225884&callback=someFunction
^^^^^^^^^^^^^^^^^^^^^^
Second: Define the callback:
// same function name as the callback in the jsonp url
function someFunction(data) {
var showStops = '';
for (var i = 0; i < data.markers.length; i++) {
showStops += '<div class="stops">';
showStops += '<h3>' + data.markers[i].smsCode + '</h3>';
showStops += '<h1>' + data.markers[i].name + '</h1>';
showStops += '</div>';
}
document.getElementById('bus-stops').innerHTML = showStops;
}
Fiddle: http://jsfiddle.net/29eajsjm/4/
Make sure the function is defined before calling the jsonp.
you have not mentioned the function name.
insead of
function (data) {
use
var myFn = function (data) {
};
or
function myFN(data) {
}
First of all validate the json you are getting from your function at jsonlint.

adding a class to an element depending on a Json feed

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

Categories

Resources