Using the `content` attribute as an HTML Template - javascript

I've been trying to use the CSS content property to make somewhat of a "template" for an element of a specific class.
I've tried multiple things. . .
Many places I have seen told me to convert everything to hexadecimal, so I did, until I saw that using hex wrote the litteral characters into the element, instead of evaluating the characters as HTML.
I then tried just litterally entering the characters into the content, and I got the exact same result (this makes it appear as if there is no purpose for the hex, yet thats hard to belive with how many people say there is. . . ).
Is there any way that I can place HTML content into an element using the CSS content attribute?
I've made a JS-Fiddle for this:
And, of course, Stack wants my source:
HTML:
<button id="normal" >Show with normal output</button>
<button id="hex" >Show with Hexadecimal output</button>
<div id="class_changer" ></div>
JS:
function changeClass(evt)
{
class_changer.className = evt.srcElement.id;
}
var class_changer = document.getElementById('class_changer');
var normal = document.getElementById('normal').addEventListener('click', changeClass, true);
var hex = document.getElementById('hex').addEventListener('click', changeClass, true);
And the un-godly long CSS:
.normal::before {
content: '<img alt="Facebook" src="http://cache.addthis.com/icons/v1/thumbs/32x32/facebook.png" />';
}
.hex::before {
content: '\0027\003c\0061\0020\0068\0072\0065\0066\003D\0022\0068\0074\0074\0070\003A\002F\002F\0061\0070\0069\002E\0061\0064\0064\0074\0068\0069\0073\002E\0063\006F\006D\002F\006F\0065\0078\0063\0068\0061\006E\0067\0065\002F\0030\002E\0038\002F\0066\006F\0072\0077\0061\0072\0064\002F\0066\0061\0063\0065\0062\006F\006F\006B\002F\006F\0066\0066\0065\0072\003F\0070\0063\006F\003D\0074\0062\0078\0033\0032\006E\006A\002D\0031\002E\0030\0026\0061\006D\0070\003B\0075\0072\006C\003D\0068\0074\0074\0070\0025\0033\0041\0025\0032\0046\0025\0032\0046\0077\0077\0077\002E\0063\0069\006D\0074\0072\0061\006B\002E\0063\006F\006D\0026\0061\006D\0070\003B\0075\0073\0065\0072\006E\0061\006D\0065\003D\0063\0069\006D\0063\006F\0072\0022\0020\0074\0061\0072\0067\0065\0074\003D\0022\005F\0062\006C\0061\006E\006B\0022\003e\003c\0069\006D\0067\0020\0061\006C\0074\003D\0022\0046\0061\0063\0065\0062\006F\006F\006B\0022\0020\0073\0072\0063\003D\0022\0068\0074\0074\0070\003A\002F\002F\0063\0061\0063\0068\0065\002E\0061\0064\0064\0074\0068\0069\0073\002E\0063\006F\006D\002F\0069\0063\006F\006E\0073\002F\0076\0031\002F\0074\0068\0075\006D\0062\0073\002F\0033\0032\0078\0033\0032\002F\0066\0061\0063\0065\0062\006F\006F\006B\002E\0070\006E\0067\0022\0020\002F\003e\003c\002F\0061\003e';
}
Check it out at JS-Fiddle and see what you can do! Let me know! Thanks everybody!
UPDATE: SOLVED (ish...)
Yes, wierd question sometimes accept wierd answers (like iterating over the DOM...) but if you have a better solution, I'm all ears.
As it turns out, the accepted answers means of evaluating a "CSS template" may be the best means of performing "templating" without the use of third-party libraries or the new <template> tag (that I'm still not sure of) even though it makes my skin crawl (if anyone has a better solution, please post it). Either way, I've updated my JSFiddle, so check it out!
Although, I guess the best answer would be purely making a template as a string in JavaScript, that is, if we are going to be evaluating it later on and pre-pending it to an element. Yea, that would make more sense...

No, this is not possible with plain CSS. However, if you really want to save these templates in CSS, you could iterate over all elements and use
window.getComputedStyle(element, ':before').content
to fetch the content and then prepend/append it to the element. To parse the HTML, you could either use jQuery.parseHTML, new DOMParser().parseFromString or a dummy DOM element. Alternatively, you could also use .innerHTML directly, but I wouldn't recommend that..

Related

Prevent Javascript Injection in data attribute

I have a script that pulls a text from an API and sets that as a tooltip in my html.
<div class="item ttip" data-html="<?php echo $obj->titleTag;?>">...</div>
The API allows html and javascript to be entered on their side for that field.
I tried this $obj->titleTag = htmlentities(strip_tags_content($this->channel->status)));
I now had a user that entered the following (or similar, he is blocked now I cannot check it again):
\" <img src="xx" onerror=window.location.replace(https://www.youtube.com/watch?v=IAISUDbjXj0)>
which does not get caught by the above.
I could str_replace the window.location stuff, but that seems dirty.
What would be the right approach? I am reading a lot of "Whitelists" but I don't understand the concept for such a case.
//EDIT strip_tags_content comes from here: https://php.net/strip_tags#86964
Well, It's not tags you're replacing now but code within tags. You need to allow certain attributes in your code rather than stripping tags since you've only got one tag in there ;)
What you wanna do is check for any handlers being bound in the JS, a full list here, and then remove them if anything contains something like onerror or so

Are HTML allowed inside HTML attributes?

For example, lets say you have something like this:
<div data-object="{'str': '<h1>This is a nice headline</h1>'}"></div>
Is this allowed in HTML5 and will it render properly in all browsers?
Edit:
With properly I mean that the browser will ignore and NOT render the H1 in any way ;)
Yes, it's allowed as long as it's quoted correctly.
Will it render? The H1 element? No - because it's not an element, it's just a bit of text inside an attribute of the div element.
Yes, browsers won't render any HTML tags inside attributes. This is pretty much common when you want to move the element later so it would show up. The only problem is that this is not a way to go as this does not create an element in DOM, thus, it will be much slower.
Try to find a way or ask for an alternative/better way to reuse the element which is hidden when the page is loaded.
Yes it's allowed and possible, but to make it work you have to make it valid JSON by using double quotes:
<div data-object='{"str": "<h1>This is a nice headline</h1>"}'></div>
Now to parse it just have: (jQuery will parse it to JSON all by itself)
var element = $("div").eq(0);
var rawData = element.data("object");
var rawHTML = rawData["str"];
$(rawHTML).appendTo("body");
Live test case.

Regex replace string but not inside html tag

I want to replace a string in HTML page using JavaScript but ignore it, if it is in an HTML tag, for example:
visit google search engine
you can search on google tatatata...
I want to replace google by <b>google</b>, but not here:
visit google search engine
you can search on <b>google</b> tatatata...
I tried with this one:
regex = new RegExp(">([^<]*)?(google)([^>]*)?<", 'i');
el.innerHTML = el.innerHTML.replace(regex,'>$1<b>$2</b>$3<');
but the problem: I got <b>google</b> inside the <a> tag:
visit <b>google</b> search engine
you can search on <b>google</b> tatatata...
How can fix this?
You'd be better using an html parser for this, rather than regex. I'm not sure it can be done 100% reliably.
You may or may not be able to do with with a regexp. It depends on how precisely you can define the conditions. Saying you want the string replaced except if it's in an HTML tag is not narrow enough, since everything on the page is presumably within some HTML tag (BODY if nothing else).
It would probably work better to traverse the DOM tree for this instead of trying to use a regexp on the HTML.
Parsing HTML with a regular expression is not going to be easy for anything other than trivial cases, since HTML isn't regular.
For more details see this Stackoverflow question (and answers).
I think you're all missing the question here...
When he says inside the tag, he means inside the opening tag, as in the <a href="google.com"> tag...This is something quite different than text, say, inside a <p> </p> tag pair or <body> </body>. While I don't have the answer yet, I'm struggling with this same problem and I know it has to be solvable using regex. Once I figure it out, i'll come back and post.
WORKAROUND
If You can't use a html parser or are quite confident about Your html structure try this:
do the "bad" changing
repeat replace (<[^>]*)(<[^>]+>) to $1 a few times (as much as You need)
It's a simple workaround, but works for me.
Cons?
Well... You have to do the replace twice for the case ... ...> as it removes only first unwanted tag from every tag on the page
[edit:]
SOLUTION
Why not use jQuery, put the html code into the page and do something like this:
$(containerOrSth).find('a').each(function(){
if($(this).children().length==0){
$(this).text($(this).text().replace('google','evil'));
}else{
//here You have to care about children tags, but You have to know where to expect them - before or after text. comment for more help
}
});
I'm using
regex = new RegExp("(?=[^>]*<)google", 'i');
you can't really do that, your "google" is always in some tag, either replace all or none
Well, since everything is part of a tag, your request makes no real sense. If it's just the <a /> tag, you might just check for that part. Mainly by making sure you don't have a tailing </a> tag before a fresh <a>
You can do that using REGEX, but filtering blocks like STYLE, SCRIPT and CDATA will need more work, and not implemented in the following solution.
Most of the answers state that 'your data is always in some tags' but they are missing the point, the data is always 'between' some tags, and you want to filter where it is 'in' a tag.
Note that tag characters in inline scripts will likely break this, so if they exist, they should be processed seperately with this method. Take a look at here :
complex html string.replace function
I can give you a hacky solution…
Pick a non printable character that’s not in your string…. Dup your buffer… now overwrite the tags in your dup buffer using the non printable character… perform regex to find position and length of match on dup buffer … Now you know where to perform replace in original buffer

JQuery $(document).ready() and document.write()

Firstly, is there a way to use document.write() inside of JQuery's $(document).ready() method? If there is, please clue me in because that will resolve my issue.
Otherwise, I have someone's code that I'm supposed to make work with mine. The catch is that I am not allowed to alter his code in any way. The part that doesn't work looks something like this:
document.write('<script src=\"http://myurl.com/page.aspx?id=1\"></script>');
The script tag is referencing an aspx page that does a series of tests and then spits out something like so:
document.write('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">')
The scripts are just examples of what is actually going on. The problem here is that I've got a document.write() in the initial script and a document.write() in the script that get's appended to the first script and I've got to somehow make this work within JQuery's $(document).ready() function, without changing his code.
I have no idea what to do. Help?
With the requirements given, no, you can't use document.write without really hosing up the document. If you're really bent on not changing the code, you can override the functionality of document.write() like so and tack on the result later:
var phbRequirement = "";
$(function() {
document.write = function(evil) {
phbRequirement += evil;
}
document.write("Haha, you can't change my code!");
$('body').append(phbRequirement);
});
Make sure you overwrite the document.write function before it is used. You can do it at anytime.
The other answers are boring, this is fun, but very pretty much doing it the wrong way for the sake of fulfilling the requirements given.
picardo has the approach I would've used. To expand on the concept, take a read:
$('<script/>')
.attr('src', 'http://myurl.com/page.aspx?id=1')
.appendTo('body');
Alternate style:
var imgnode = $('<img alt="Second image for id 1"/>')
.attr('src', "image1.jpg");
$('#id1').append(imgnode);
Be sure to use the attr method to set any dynamic attributes. No need to escape special symbols that way.
Also, I'm not sure what the effectiveness of dynamically generating script tags; I never tried it. Though, it's expected that they contain or reference client-side script. My assumption is that what page.aspx will return. Your question is a little vague about what you're trying to do there.
jQuery has a ready substitute for document.write. All you need to use is the append method.
jQuery('<img src=""/>').appendTo('body');
This is fairly self-evident. But briefly, you can replace the with whatever html you want. And the tag name in the appendTo method is the name of the tag you want to append your html to. That's it.
picardo's answer works, but this is more intuitive for me:
$("body").append('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">');
Also, for the script part that is being inserted with document.write(), check out jQuery's getScript() function

How to store arbitrary data for some HTML tags

I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:
<a class="article" href="#5">
I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example)
Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)
The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).
<a articleid="5" href="link/for/non-js-users.html">
In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.
Another method I'd used in the past was to actually generate some JS and insert it into the page in a <script> tag, creating a struct which would associate with the object.
var myData = {
link0 : {
articleId : 5,
target : '#showMessage'
// etc...
},
link1 : {
articleId : 13
}
};
<a href="..." id="link0">
But this can be a real pain in butt to maintain and is generally just very messy.
So, to get to the question, how do you store arbitrary pieces of information for HTML tags?
Which version of HTML are you using?
In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.
<div data-internalid="1337"></div>
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.
If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery.
To store something:
$('#myElId').data('nameYourData', { foo: 'bar' });
To retrieve data:
var myData = $('#myElId').data('nameYourData');
That is all that there is to it but take a look at the jQuery documentation for more info/examples.
Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).
<a class="article" href="link/for/non-js-users.html">
<span style="display: none;">{"id": 1, "title":"Something"}</span>
Text of Link
</a>
// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);
Arbitrary attributes are not valid, but are perfectly reliable in modern browsers. If you are setting the properties via javascript, than you don't have to worry about validation as well.
An alternative is to set attributes in javascript. jQuery has a nice utility method just for that purpose, or you can roll your own.
A hack that's going to work with pretty much every possible browser is to use open classes like this: <a class='data\_articleid\_5' href="link/for/non-js-users.html>;
This is not all that elegant to the purists, but it's universally supported, standard-compliant, and very easy to manipulate. It really seems like the best possible method. If you serialize, modify, copy your tags, or do pretty much anything else, data will stay attached, copied etc.
The only problem is that you cannot store non-serializable objects that way, and there might be limits if you put something really huge there.
A second way is to use fake attributes like: <a articleid='5' href="link/for/non-js-users.html">
This is more elegant, but breaks standard, and I'm not 100% sure about support. Many browsers support it fully, I think IE6 supports JS access for it but not CSS selectors (which doesn't really matter here), maybe some browsers will be completely confused, you need to check it.
Doing funny things like serializing and deserializing would be even more dangerous.
Using ids to pure JS hash mostly works, except when you try to copy your tags. If you have tag <a href="..." id="link0">, copy it via standard JS methods, and then try to modify data attached to just one copy, the other copy will be modified.
It's not a problem if you don't copy tags, or use read only data. If you copy tags and they're modified you'll need to handle that manually.
Using jquery,
to store: $('#element_id').data('extra_tag', 'extra_info');
to retrieve: $('#element_id').data('extra_tag');
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
You could use hidden input tags. I get no validation errors at w3.org with this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
<title>Hello</title>
</head>
<body>
<div>
<a class="article" href="link/for/non-js-users.html">
<input style="display: none" name="articleid" type="hidden" value="5" />
</a>
</div>
</body>
</html>
With jQuery you'd get the article ID with something like (not tested):
$('.article input[name=articleid]').val();
But I'd recommend HTML5 if that is an option.
Why not make use of the meaningful data already there, instead of adding arbitrary data?
i.e. use <a href="/articles/5/page-title" class="article-link">, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/ against this.href).
As a jQuery user I would use the Metadata plugin. The HTML looks clean, it validates, and you can embed anything that can be described using JSON notation.
This is good advice. Thanks to #Prestaul
If you are using jQuery already then you should leverage the "data"
method which is the recommended method for storing arbitrary data on a
dom element with jQuery.
Very true, but what if you want to store arbitrary data in plain-old HTML? Here's yet another alternative...
<input type="hidden" name="whatever" value="foobar"/>
Put your data in the name and value attributes of a hidden input element. This might be useful if the server is generating HTML (i.e. a PHP script or whatever), and your JavaScript code is going to use this information later.
Admittedly, not the cleanest, but it's an alternative. It's compatible with all
browsers and is valid XHTML. You should NOT use custom attributes, nor should you really use attributes with the 'data-' prefix, as it might not work on all browsers. And, in addition, your document will not pass W3C validation.
As long as you're actual work is done serverside, why would you need custom information in the html tags in the output anyway? all you need to know back on the server is an index into whatever kind of list of structures with your custom info. I think you're looking to store the information in the wrong place.
I will recognize, however unfortunate, that in lots of cases the right solution isn't the right solution. In which case I would strongly suggest generating some javascript to hold the extra information.
Many years later:
This question was posted roughly three years before data-... attributes became a valid option with the advent of html 5 so the truth has shifted and the original answer I gave is no longer relevant. Now I'd suggest to use data attributes instead.
<a data-articleId="5" href="link/for/non-js-users.html">
<script>
let anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let articleId = anchor.dataset.articleId;
}
</script>
I advocate use of the "rel" attribute. The XHTML validates, the attribute itself is rarely used, and the data is efficiently retrieved.
So there should be four choices to do so:
Put the data in the id attribute.
Put the data in the arbitrary attribute
Put the data in class attribute
Put your data in another tag
http://www.shanison.com/?p=321
You could use the data- prefix of your own made attribute of a random element (<span data-randomname="Data goes here..."></span>), but this is only valid in HTML5. Thus browsers may complain about validity.
You could also use a <span style="display: none;">Data goes here...</span> tag. But this way you can not use the attribute functions, and if css and js is turned off, this is not really a neat solution either.
But what I personally prefer is the following:
<input type="hidden" title="Your key..." value="Your value..." />
The input will in all cases be hidden, the attributes are completely valid, and it will not get sent if it is within a <form> tag, since it has not got any name, right?
Above all, the attributes are really easy to remember and the code looks nice and easy to understand. You could even put an ID-attribute in it, so you can easily access it with JavaScript as well, and access the key-value pair with input.title; input.value.
One possibility might be:
Create a new div to hold all the extended/arbitrary data
Do something to ensure that this div is invisible (e.g. CSS plus a class attribute of the div)
Put the extended/arbitrary data within [X]HTML tags (e.g. as text within cells of a table, or anything else you might like) within this invisible div
Another approach can be to store a key:value pair as a simple class using the following syntax :
<div id="my_div" class="foo:'bar'">...</div>
This is valid and can easily be retrieved with jQuery selectors or a custom made function.
In html, we can store custom attributes with the prefix 'data-' before the attribute name like
<p data-animal='dog'>This animal is a dog.</p>.
Check documentation
We can use this property to dynamically set and get attributes using jQuery like:
If we have a p tag like
<p id='animal'>This animal is a dog.</p>
Then to create an attribute called 'breed' for the above tag, we can write:
$('#animal').attr('data-breed', 'pug');
To retrieve the data anytime, we can write:
var breedtype = $('#animal').data('breed');
At my previous employer, we used custom HTML tags all the time to hold info about the form elements. The catch: We knew that the user was forced to use IE.
It didn't work well for FireFox at the time. I don't know if FireFox has changed this or not, but be aware that adding your own attributes to HTML elements may or may-not be supported by your reader's browser.
If you can control which browser your reader is using (i.e. an internal web applet for a corporation), then by all means, try it. What can it hurt, right?
This is how I do you ajax pages... its a pretty easy method...
function ajax_urls() {
var objApps= ['ads','user'];
$("a.ajx").each(function(){
var url = $(this).attr('href');
for ( var i=0;i< objApps.length;i++ ) {
if (url.indexOf("/"+objApps[i]+"/")>-1) {
$(this).attr("href",url.replace("/"+objApps[i]+"/","/"+objApps[i]+"/#p="));
}
}
});
}
How this works is it basically looks at all URLs that have the class 'ajx' and it replaces a keyword and adds the # sign... so if js is turned off then the urls would act as they normally do... all "apps" (each section of the site) has its own keyword... so all i need to do is add to the js array above to add more pages...
So for example my current settings are set to:
var objApps= ['ads','user'];
So if i have a url such as:
www.domain.com/ads/3923/bla/dada/bla
the js script would replace the /ads/ part so my URL would end up being
www.domain.com/ads/#p=3923/bla/dada/bla
Then I use jquery bbq plugin to load the page accordingly...
http://benalman.com/projects/jquery-bbq-plugin/
I have found the metadata plugin to be an excellent solution to the problem of storing arbitrary data with the html tag in a way that makes it easy to retrieve and use with jQuery.
Important: The actual file you include is is only 5 kb and not 37 kb (which is the size of the complete download package)
Here is an example of it being used to store values I use when generating a google analytics tracking event (note: data.label and data.value happen to be optional params)
$(function () {
$.each($(".ga-event"), function (index, value) {
$(value).click(function () {
var data = $(value).metadata();
if (data.label && data.value) {
_gaq.push(['_trackEvent', data.category, data.action, data.label, data.value]);
} else if (data.label) {
_gaq.push(['_trackEvent', data.category, data.action, data.label]);
} else {
_gaq.push(['_trackEvent', data.category, data.action]);
}
});
});
});
<input class="ga-event {category:'button', action:'click', label:'test', value:99}" type="button" value="Test"/>
My answer might not apply to your case. I needed to store a 2D table in HTML, and i needed to do with fewest possible keystrokes. Here's my data in HTML:
<span hidden id="my-data">
IMG,,LINK,,CAPTION
mypic.jpg,,khangssite.com,,Khang Le
funnypic.jpg,,samssite.com,,Smith, Sam
sadpic.png,,joyssite.com,,Joy Jones
sue.jpg,,suessite.com,,Sue Sneed
dog.jpg,,dogssite.com,,Brown Dog
cat.jpg,,catssite.com,,Black Cat
</span>
Explanation
It's hidden using hidden attribute. No CSS needed.
This is processed by Javascript. I use two split statements, first on newline, then on double-comma delimiter. That puts the whole thing into a 2D array.
I wanted to minimize typing. I didn't want to redundantly retype the fieldnames on every row (json/jso style), so i just put the fieldnames on the first row. That a visual key for the programmer, and also used by Javascript to know the fieldnames. I eliminated all braces, brackets, equals, parens, etc. End-of-line is record delimiter.
I use double-commas as delimiters. I figured no one would normally use double-commas for anything, and they're easy to type. Beware, programmer must enter a space for any empty cells, to prevent unintended double-commas. The programmer can easily use a different delimiter if they prefer, as long as they update the Javascript. You can use single-commas if you're sure there will be no embedded commas within a cell.
It's a span to ensure it takes up no room on the page.
Here's the Javascript:
// pull 2D text-data into array
let sRawData = document.querySelector("#my-data").innerHTML.trim();
// get headers from first row of data and load to array. Trim and split.
const headersEnd = sRawData.indexOf("\n");
const headers = sRawData.slice(0, headersEnd).trim().split(",,");
// load remaining rows to array. Trim and split.
const aRows = sRawData.slice(headersEnd).trim().split("\n");
// trim and split columns
const data = aRows.map((element) => {
return element.trim().split(",,");
});
Explanation:
JS uses lots of trims to get rid of any extra whitespace.

Categories

Resources