I have hundreds of HTML pages and I would like to add a new div with link and style to them but editing each page takes lots of time.
All the pages have one common JavaScript file.
how can I append or add below div to all the pages?
<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>
avoid-fout is a class and I tried to add below code but it's not working.
$(".avoid-fout").append("<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>");
When appending, make sure you observe the use of single and double quotes, as shown below
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>');
Use single quote first, then everything inside should be done with double quotes, or vice versa.
Try this
$(".avoid-fout").append(`<div style="background-color:#561D1B;" id="testid"> <marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>`);
Also make sure, your script src is a valid JS
Your .append call will not work because you are appending a string with double quotes, and also using double-quotes in the html. Simplest fix is to use single quotes for your html string instead:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>');`
If you do not want to use Jquery or avoid inserting HTML string, this might help. It uses vanilla JS dom APIs. You can modify the method appendToElem in case you need to add any other stuff
function appendToElem(elem) {
if (!elem) {
console.error(elem)
}
var script = document.createElement('script')
script.setAttribute("src", "https://testurl.com/test")
script.setAttribute("type", "text/javascript")
var marquee = document.createElement('marquee')
marquee.style.backgroundColor = "#561D1B"
marquee.style.height = "19px"
marquee.appendChild(script)
var div = document.createElement("div")
div.id = "testid"
div.style.backgroundColor = "#561D1B"
div.appendChild(marquee)
elem.appendChild(div)
}
appendToElem(document.getElementsByClassName('avoid-fout')[1])
<div class="avoid-fout">
<h2>Some Random title</h2>
<p>Some Text</p>
</div>
<div class="avoid-fout">
<h2>Add At the end of this container</h2>
<p>
Add the asked div, with marquee and script below this.
</p>
</div>
There are a couple of problems. You are trying to use double-quotes inside of a double quoted string, you can't do that without escaping the double quotes.
"This is "not" a valid string";
"This \"is\" a valid string";
A simple solution to this that I usually use is to just use single quotes to encapsulate HTML and only use double-quotes in my HTML:
'<div id="double-quotes-work-here">Just can\'t use unescaped single-quotes</div>';
The other problem is that you are trying to use a string that spans multiple lines. Single and double quoted strings in JS can generally not include any new line characters. In cases like this where you are just inserting HTML and the new lines don't actually matter, the easiest thing to do would be to just delete the new lines and include all the HTML on one line:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid"> <marquee style="background-color:#561D1B;height:19px;">Foo</marquee> </div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
If you want to keep it on multiple lines, there are a few options.
You could use multiple concatenated strings:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">' +
'<marquee style="background-color:#561D1B;height:19px;">Foo</marquee>' +
'</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
Or you could escape the new-lines by using \:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">\
<marquee style="background-color:#561D1B;height:19px;">Foo</marquee>\
</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
This way should be avoided though. It is fairly error-prone, if there is any white space after the \, it will cause a syntax error; one that is really hard to notice since the white space is not visible. For instance:
'this is a valid\
multi-line string';
'this is not a valid\
multi-line string';
See the difference? Me neither.
If the browsers you are targeting all support it (most modern browser do), I would use a template literal:
$(".avoid-fout").append(`<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;">Foo</marquee>
</div>`);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
Template literals allow you to use multi-line strings without any escaping, you can use both single and double quotes inside of them without escaping them. They also allow you to do other neat things like expression interpolation and using tagged templates.
Learning to use the developer console in your browser, as well as a linter, such as jsHint can help a lot with spotting errors like these.
Related
I've got div on my page with id attribute with escaped HTML for example:
<div class="myDiv" id="<script>alert(1)</script>></div>
Can I with JavaScript and JQuery take the value of this attribute as it is coded? Using just $('.myDiv').attr('id) im just getting <script>alert(1)</script> and I have to know if this HTML has already been escaped :O
Just need to get this attribute in JS as <script>alert(1)</script>
https://i.stack.imgur.com/vXmVK.png
You might consider something safer. You must also wrap it properly. Your example is missing a closing Quote.
<div class="myDiv" id="myDiv-1" data-script="alert(1)"></div>
You could also do it this way.
<div class="myDiv" id="myDiv-1" data-script="<script>alert(1)</script>"></div>
Again this is not good practice. You may want to consider another method.
I'm experimenting with the < pre> and < code> tags in html 5 as I would like to include some code snippets on my website. I'm using the page below as a test page but it is not displaying anything. Any reason why?
<body>
<div style="color:#000000">
<pre>
<code>
<script type="text/javascript">
$('#inputField').hide();
</script>
</code>
</pre>
</div>
</body>
It was my understanding that using these new tags would negate any code that they contain within however this does not appear to be the case.
Cheers,
J
These tags are only for "decorational" purposes. Code within will still be executed. If you want it displayed you have to convert at least the <script> tag to html:
<script type="text/javascript">
Then the JavaScript code inbetween will be shown.
You don't need both though, I would use <pre> (which is per default a block element), <code> is intended for inline use.
Remove script tag:
<body>
<div style="color:#000000">
<pre>
<code>
$('#inputField').hide();
</code>
</pre>
</div>
</body>
It was my understanding that using these new tags would negate any code that they contain
They don't. They tell user agents to present the data as code. So it will have font changes, white space will be significant, it should be skipped over by translation software and so on.
Markup still takes effect (so you can add elements to style, or link the code to other places, and so on) so you still need to replace HTML special characters (<, &, etc) with their respective entities (<, &, etc).
This would work if you take the script tags out.
These code tags only change the font of the text inside to a monospace font, however it does not override the interpretation of other tags (or even php tags).
A better way is to use CSS to get color highlighting, or javascript libraries.
I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'
I have a JavaScript string containing HTML like this:
<div>
<div class="a">
content1
</div>
content 2
<div class="a">
<b>content 3</b>
</div>
</div>
and I want to remove the div's of class="a" but leave their content.
In Python I would use something like:
re.compile('<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)
What is the equivalent using Javascript regular expressions?
Why don't you use proper DOM methods? With a little help from jQuery, that's dead simple:
var contents = $('<div><div class="a">content1</div>content 2<div class="a"><b>content 3</b></div></div>');
contents.find('.a').each(function() {
$(this).replaceWith($(this).html());
});
You can achieve it with regular expressions in JavaScript
var html = '<div> <div class="a"> content1 </div> <div class="a"> content1 </div> ... </div>';
var result = html.replace(/<div class="a">(.*?)<\/div>/g, function(a,s){return s;});
alert(result);
RegExp method replace takes two parameters - first one is the actual re and the second one is the replacement. Since there is not one but unknown number of replacements then a function can be used.
If you want to do this in Javascript, I'm presuming that you are running it in a web browser, and that the 'javascript string' that you refer to was extracted from the DOM in some way.
If both of these case are true, then I'd say that it would be a good idea to use a tried and tested javascript library, such as JQuery (There are others out there, but I don't use them, so can't really comment)
JQuery allows you to do on-the-fly DOM manipulations like you describe, with relative ease...
$('div.a').each(function(){$(this).replaceWith($(this).html());});
JQuery is definitely one of those tools that pays dividends - a failry short learning curve and a whole lot of power.
Here's my code:
<a href="#">
<img src="myimage.jpg"
onmouseover="showDescription(
'Text', 'Text with HTML tags in them<br />More text');"
onmouseout="revertDescription();"
alt="Image description">
The W3C Markup Validator doesn't like this. It doesn't want HTML tags inside my JavaScript code. Here's the error message it produces if I attempt this:
character "<" is the first character of a delimiter but occurred as data
How can I fix this while making sure that my page doesn't mess up if I pass the HTML tag-containing string to document.getElementById('myElement').innerHTML?
You could wrap your functions inside separate <script>...</script> tags somewhere else in the document, and there use ...
<script>
//<![CDATA[
...code...
//]]>
</script>
From http://javascript.about.com/library/blxhtml.htm:
To fix this problem wer can do one of two things. The simplest way, particularly if the Javascript contains more than just one or two lines, is to make the Javascript external to the page resulting in their being nothing between the script tags to stop the page validating.
If it is just one or two lines then it is probably not worth making an external script so you will want to leave the content between the script tags and tell the validator that this is to be ignored. We do this by placing the Javascript code within a CDATA tag like this ...
There are many ways to get there.
Use < or < instead of <
Use > or > instead of >
Get a id to the image, such as "image1", then
document.getElementById("image1").onmouseover = showDescription(
'Text', 'Text with HTML tags in them<br />More text');
Hope this works.
onmouseover="showDescription('Text', 'Text with HTML tags in them<br />More text');"
Like with all attribute values, you must HTML-encode &, <, and the attribute delimiter (" here). The fact that it's JavaScript inside the attribute value makes no difference; the HTML attribute value is decoded before JavaScript gets a look at it.
onmouseover="showDescription('Text', 'Text with HTML tags in them<br />More text');"
This is in contrast to a <script> element, whose contents are CDATA and thus not &-escaped in HTML4. In XHTML there are no CDATA elements; you can add a <![CDATA[ section to make XHTML behave the same, but it's usually simpler for both script elements and event handler attributes to just avoid the problem by never using a & or < character. In a string literal another escape is available which you can use to get around this:
onmouseover="showDescription('Text', 'Text with HTML tags in them\x3Cbr />More text');"
Replace < by %3C and > by %3E and use unescape when outputting the contents.
This won't validate:
function(){
return ('<b> bold </b>');
}
This gives the same results and validates:
function(){
return unescape('%3Cb%3E bold %3C/b%3E');
}
How about putting this within a <script ...> block:
var myText = 'Text with HTML tags in them<br />More text';
And later in your HTML:
<a href="#">
<img src="myimage.jpg"
onmouseover="showDescription(
'Text', myText);"
onmouseout="revertDescription();"
alt="Image description">