I would like to say
<html>
<body>
<mytag foo="bar">blah</mytag>
</body>
</html>
And define somewhere else how a <mytag> should behave. But for older browsers that do not play nicely with custom tags, I would like to just load a js library in the browser and have it automatically rewrite the above code as say
<html>
<body>
<div data-mytag data-foo="bar">blah</div>
</body>
</html>
Obviously this functionality could be hacked together in an hour, but I would prefer to use a tiny library that someone has written, for the sake of convention and possibly handy features. Do you know of one? Note: please don't reply about why I shouldn't use custom tags.
For the first part, maybe something like
<mytag>yo</mytag>
<script>
var map = {
MYTAG: function(s){
// surround content with stars
return '**'+s+'**';
}
}
Array.prototype.slice.call(document.getElementsByTagName('*')).forEach(function(tag){
// note on some IE versions you cant set innerHTML directly
if(map[tag.tagName]) tag.innerHTML = map[tag.tagName](tag.innerHTML);
})
</script>
For changing element tags at runtime, I can't recall if that's possible. People may cringe, but I'd maybe take the entire document.body.innerHTML replace it using regexes and reset it. If I knew I was the only creator of the HTML content that may take care of it..
Related
So I have been using v-html tag to render the html in my vue pages.
But I encountered a string which was a proper html file and it contained text kind of like this:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
....
<style>
</style>
</head>
<body style="....">
</body>
</html>
The problem is, I have the v-html on a div, but this code starts affecting the whole page and adds its styling to the whole page and not only to that specific div.
I tried adding "scope" to the style tags but it did not work. Maybe because there's also a style inline tag on body?
I need to find a way to make the html affect only on the div it is on, and not the whole page.
Your best bet would probably be to have a better control over the HTML added using v-html. I would suggest to parse it before and keep only the <body> tag. You could do it using a regex, but it would be easier using a dom parser lib. Example with DomParser:
const DomParser = require("dom-parser");
const parser = new DomParser();
export default {
// ...
computed: {
html() {
const rawHtml = "<html><body><div>test</div></body></html>"; // This data should come from your server
const dom = parser.parseFromString(rawHtml);
return dom.getElementsByTagName("body")[0].innerHTML;
}
}
}
Please note that it is an oversimplified solution as it does not handle the case where there is no <body> tag.
First, you should be very careful when using external HTML with v-html as it can make your site vulnerable to various sorts of attacks (see Vue docs).
Now if you trust the HTML source, other problem is how to embed it without affecting your own side. There is special element for this case, <iframe> - it is not without risk and you should definitely read a bit on how to make it safe but it should solve your problem because is "sandbox" external HMTL so it does not affect your site.
https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies
I want a Tumblr theme to add link-able anchors to every header in the content of a post. I don't have access to, or control over, the rendering of that content; Tumblr tends to spit out plain <h2>s and similar, for Markdown headers:
## Hello, 💖 friend 💝! -> <h2>Hello, 💖 friend 💝!</h2>
I'd like to ensure that any section of a post can be hyperlinked directly to with an anchor link, such as http://thing.place/post/12345#hello-friend. Has anybody got a simple, fairly universal JavaScript snippet to sanitize any header element's content, and add it to that header as an id?
(Presumably, if you've already written this for yourself; you might also have some additional code to add an anchor-link indicator that self-links, as well; share it if you've got it.)
I maintain a project that does what you describe: AnchorJS
Docs: http://bryanbraun.github.io/anchorjs/
Github Repo: https://github.com/bryanbraun/anchorjs
Once you include the script, you can pick which elements it adds anchors to with a selector:
// Add anchors to all h1's and h2's on the page
anchors.add('h1, h2');
It doesn't have any dependencies on Jquery or Lodash, in case that's an issue with Tumblr (I'm not familiar enough with Tumblr to know the constraints there).
I've got a really naïve solution that depends upon both jQuery and Lodash (and I do mean full jQuery, as Zepto and friends don't include :header); but lightweight, elegant, pure-JavaScript solutions are preferred:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<script>
jQuery.noConflict(true)(function($){
var lodash = _.noConflict()
, anchor = "\u2693\uFE0E"
$(':header')
.wrap(function(){
var wrapper = document.createElement('header')
, title = lodash.kebabCase( $(this).text() )
return $(wrapper).attr('id', title) })
})
</script>
This does the extra work of adding a semantic <header> element that I'm planning on using for other purposes, but that may not be necessary.
This question already has answers here:
Is there a way to create your own html tag in HTML5?
(18 answers)
Closed 8 years ago.
Would it be possible to do the following
<body>
<main>
<!-- CONTENT -->
</main>
<foot>
<!-- FOOTER CONTENT -->
</foot>
</body>
if I then wrote some JavaScript that did something along the lines of the following. Please note that I don't want you to write the actual code that goes here. This is just a mockup of the core functionality.
for(elem inside main){
elem.makeItBig();
}
for(elem inside foot){
if(elem is img){
elem.makeItSmall();
}
}
I am aware of this post Is there a way to create your own html tag in HTML5?. But I don't really want to create tags to style them but rather to provide identifying attributes to the DOM which I can hook into using JavaScript. Imagine something kind of like a class, but used in a way that you can stitch lots of PHP generated parts together using these tags.
If you use a made up tag in HTML is it ignored by your browser or will it throw an error.
You can use your own tags as far as I'm aware.
You'd need to do some mucking about to get them to work in older IE browsers.
The more important point is - why on earth would you want to? It wouldn't make your code very maintainable or future-proof. Just use classes on proper elements.
Can you create custom tags? yes. Is it a good idea? not really because your tag may not be recognized by some browsers as a valid html standard. you can check this: http://www.w3.org/MarkUp/html-spec/html-spec_4.html#SEC4.2.1
For custom elements specifications you can look at standards specification for custom elements : http://w3c.github.io/webcomponents/spec/custom/
Although your approach seems nice, just think about changing the size of another group of elements ... you would probably use the same function so why not do this:
var makeItBig = function(elem){...};
for(elem in main){
makeItBig(main[elem]);
}
this way you won't have to create a new method for each element you need to change.
But if you really need it that way you can make it like this:
var makeItBigFunction = function(){var elem = this; ...};
// create new methods
for(elem in main){
main[elem].makeItBig = makeItBigFunction;
}
// make use of them
for(elem in main){
main[elem].makeItBig();
}
Notice that there is a big difference between DOM object's properties (or methods) and HTML attributes.
Read more about it: Properties and Attributes in HTML
Feel free to use HTML5 tags like <content>, <header>, <footer>, <aside> etc.
You can read more about them here: http://www.w3schools.com/html/html5_new_elements.asp in section "New Semantic/Structural Elements". Those should be considered as supported in most modern browsers. Actually, you may use any other custom tags, however their default properties (display, position etc.) may be unpredictable.
We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas
Today I stumbled upon the possibility to access a DOM element in Javascript simply by its id e.g. like this:
elementid.style.backgroundColor = "blue"
I tested with a very short snippet if this works in IE, Firefox and Chrome - and it does.
Here is the snippet I used:
<html><head>
<script>
function highlight() {
content.style.backgroundColor = "blue";
content.style.color = "white";
}
</script>
</head>
<body>
<div id="content">test content</div>
<div onclick="highlight()">highlight content</div>
</body></html>
So I wondered in which cases document.getElementById('elementid') should be used (or similar framework replacements like $()) and what are the drawbacks of the direct access.
I was not able to find any useful documentation on this. Everywhere either getElementById or framework methods are used.
It is propriety Microsoft gubbins. It doesn't work in lots of browsers — especially in standards mode (and you want standards mode to avoid quirks mode inconsistencies such as IE getting width wrong).
You should also be concerned about name space. Right now you're treating it as if it's a variable in the global name space, and you would have to trust neither you nor any libraries that you include declare any global variables with the same name as DOM id's. The same goes for your highlight function.
Also while id's with dashes are perfectly valid, those would be inaccessible via this method.
e.g. <div id="container-wrapper"><div id="container"> ... </div></div>
would become container-wrapper.style.color which would then try to subtract wrapper.style.color from container.
It’s not a part of any standard. Besides, simple variables can be overwriten. Var content could be redeclared in any place of your script, or external library (and, yes, I know global variables are evil, but ppl still use them…) and your script will break.
And, naturally, you cannot use IDs like alert or document etc.