I am using CEWP (webpart) and putting this code in there. But this code is not going inside <head> tag. I need to insert this code in <head> tag,
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$("*").each(function () { if ($(this).children().length == 0) { $(this).text($(this).text().replace('Respuesta','Responder')); } });
</script>
How can I do this? How this code will work in CEWP webpart?
Firstly, you can put the code in the <head> if you set it to run at document ready time.
However, it's still not going to work. You're iterating over all tags. Including <html>, which will be the first one selected by $('*').
So you read all the text inside the <html> element (ie. the entire document text), do a string replace on it, then write it back to the html text(). Replacing all the previous text and element content of the <html> element with a single simple text string. And thereby destroying every other element on the page. Oops.
What you want to do is find every text node and do a separate string replace on it:
$(document).ready(function() {
$('*').each(function() {
for (var i= this.childNodes.length; i-->0;) {
var child= this.childNodes[i];
if (child.nodeType===3) // TEXT_NODE
child.data= child.data.replace(/Respuesta/g, 'Responder');
}
});
});
(Note there are still a bunch of possible edge cases here with form fields and other elements where changing the text inside them might not do what you expect.)
Related
This should be a pretty easy thing to do, but it's not returning anything.
The function love() should kick off, getting a simple number prompt, and spitting out a list of a few items that uses that starting number.
the alert box correctly displays what I expect, but I want it to display on the screen.
(this is but a small section of what I'm after, but it's the kernel of it). No text is displaying in the IE, FF, or Chrome...
<script type="text/javascript">
function love()
{
var ncxElement="";
var idNumber = prompt("Enter beginning number","");
var myText=document.getElementById("here");
for (var i=1;i<5;i++)
{
ncxElement+=("<navPoint class=\"other\" id=\"page_"+idNumber+"\">\n");
idNumber++;
}
alert(ncxElement);
myText.innerHTML=ncxElement;
}
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>
If you want to display HTML on your page (without it being parsed), use .textContent instead of .innerHTML and wrap it in a <pre> (to preserve the line breaks).
Demo:
Change:
myText.innerHTML=ncxElement;
To:
myText.textContent=ncxElement;
Change:
<p id="here">Begin!</p>
To:
<pre id="here">Begin!</pre>
navPoints are not valid html elements, so the browser doesn't know what to do with them. They are being added to the DOM, just not displayed unless you add styling to do so.
If you replace them with paragraph tags, it works fine. See the example here.
<script type="text/javascript">
function love()
{
var ncxElement="";
var idNumber = prompt("Enter beginning number","");
var myText=document.getElementById("here");
for (var i=1;i<5;i++)
{
ncxElement+=("<p class=\"other\" id=\"page_"+idNumber+"\">"+idNumber+ "</p>");
idNumber++;
}
alert(ncxElement);
myText.innerHTML=ncxElement;
}
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>
Your function just wraps elements inside another. There is no text inside or outside these elements to dipslay.
Try inserting some random text before closing tags to see the result.
Btw, the elements are successfully placed in the p tag.
I have a problem, I wanted to create a div in html as a container and in javascript create new divs within the container based on a number input from a user prompt.
My html and javascript look like this.
HTML:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>Sketchpad</title>
</head>
<body>
<button type="button">Reset</button>
<div class= "container">
</div>
<script src="javascript.js"></script>
<script src="jQuery.js"></script>
</body>
JS
var row = prompt("Enter number of rows:");
var column = prompt("Enter number of columns:");
function createGrid(){
var cont = document.getElementsByClassName('container');
for(i=1; i<column; i++){
var sketchSquare = document.createElement('div');
cont.appendChild(sketchSquare);
}
}
createGrid(column);
I end up with this error: Uncaught TypeError: cont.appendChild is not a function.
I imagine this is something to do with the getElementsByClassName?
I do have a solution which involves creating the container div in javascript and appending the smaller squares inside the container div. I was just curious as to why my first soltuion didn't work?
cont[0].appendChild(myDiv) is a function.
When you document.getElements By Class Name as the name implies you are getting many elements (an array of sorts) of elements and this array don't have the same functions as each of its elements.
Like this:
var thinkers = [
{think: function(){console.log('thinking');}
];
thinkers don't have the method .think
but thinkers[0].think() will work.
try this: open your javascript console by right clicking and doing inspect element:
then type:
var blah = document.getElementsByClassName('show-votes');
blah[0].appendChild(document.createElement('div'));
It works!
also if you want to use jQuery which I do see you added...
you can do:
var cont = $('container');
cont.append('<div class="sketchSquare"></div>');
Try that out by doing this:
First get an environment that has jQuery.
Hmm maybe the jQuery docs have jQuery loaded!
They do: http://api.jquery.com/append/.
Open the console there and at the bottom where the console cursor is type:
$('.signature').append('<div style="background: pink; width: 300px; height: 300px"></div>');
You'll notice that you add pink boxes of about 300px^2 to 2 boxes each of which have the "signature" class.
By the way, prompt gives you a string so you'll have to do row = Number(row); or row = parseInt(row, 10); and another thing don't use that global i do for(var i = 0; ...
var cont = document.getElementsByClassName('container');
Because that^ doesn't return a node, it'll return an HTMLCollection.
https://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0
You need to pick an individual node from that collection before appending.
There could be a couple of issues that could cause this. Without fully giving the answer here's what it could be at a high level.
Your script is ran before the DOM is fully loaded. Make sure that your script is ran after the DOM is present in the page. This can be accomplished using either the DOMReady event ($(document).ready equivalent without jQuery) or simply making sure your script tag is the last element before the closing body tag. (I usually prefer the former)
When you utilize document.getElementsByClassName('container') (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) this method returns an array therefore you would either need to apply the operation to all elements of the result or just select the zero-th as document.getElementsByClassName('container')[0]. As an alternative, if you would like to be more explicit you could also place an id on the container element instead to more explicitly state which element you would like to retrieve. Then, you would simply use document.getElementById([id]) (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and this would get back a single element not a collection.
The result of prompt is a string. Therefore you would have to first parse it as an integer with parseInt(result, 10) where 10 is simply the radix or more simply you want a number that is from 0-10.
You should include jquery library before your script, it`s important
<script src="jQuery.js"></script>
<script src="javascript.js"></script>
How can I replace text on a page using jQuery without replacing tags and text within tags such as: <a>,<input>,<button>,<textarea>,<input>,<select>.
For example, here is the HTML code
<html>
<head>
<title>Testing</title>
</head>
<body>
Hello, this is a test replacing {REPLACE_ME} with <b>{REPLACED}</b>.
<br/><br/>
I want {REPLACE_ME} and {REPLACE_ME} to be <b>{REPLACED}</b>, however I don't want this {REPLACE_ME} to become {REPLACED}.
Same with <textarea>{REPLACE_ME}</textarea>, it shouldn't change.
<br/><br/>
</body>
I have this jQuery to replace the text
var replaced = $("body").html().replace(/{REPLACE_ME}/gi,'<b>{REPLACED}</b>');
$("body").html(replaced);
Here it is on JSFiddle
http://jsfiddle.net/E8ZPY/
$('body, body *:not(a,button,textarea,option)').contents().filter(function() {
return this.nodeType === 3;
}).each(function() {
var escaped = $('<div></div>').text($(this).text()).html();
$(this).replaceWith(escaped.replace(/\{REPLACE_ME\}/gi,'<b>{REPLACED}</b>'));
});
JSFiddle
(I didn't need to include input, and I used option instead of select, since option is the one with text nodes for children.)
first add jquery file
apply "\" in regex pattern for special character
var replaced = $("body").html().replace(/\{REPLACE_ME\}/gi,'<b>{REPLACED}</b>');
// see here^^^__________^^^^
$("body").html(replaced);
see updated fiddle
var replaced = $("body").html().replace(/[^>]{REPLACE_ME}[^<]*/gi, '<b>{REPLACED}</b>');
$("body").html(replaced);
I have an editable DIV in my site to send a forum message. People can edit their messages (Bold, Italic, underline, add links and more)
But I want when some one paste or drop (- drop is not necessary, but paste it is) their text I want it to go in the DIV without HTML tags - clean, just text. (like if some one is going to word and make the text 200 points size, then copy & paste it in my DIV, they will have a very different message... and I don't want it to happen).
How can I scan the text coming from the clipboard to remove any HTML tags and then paste it in the DIV?
<html>
<head>
<script type="text/javascript" language="javascript">
function PasteFilter()
{
//windows.clipboardData filter on paste to go here
}
function CopyFilter()
{
//windows.clipboardData filter on copy to go here
}
</script>
</head>
<body>
<Div class="body" onpaste="PasteFilter()" oncopy="CopyFilter">
<!-- div content goes here.-->
</Div>
</body>
</html>
I would like to also apply the same filter with COPY too.
Thanks
I believe there are 2 ways to do this:
1) The easy way - insert the following code in PasteFilter():
var foo = window.clipboardData.getData('Text');
window.clipboardData.setData('Text', foo);
the first line gets the Text value of clipboardData (already stripped of HTML tags)
and the second line sets the clipboardData to the plain text...
(Tested on IE8)
2) The other way - if for some reason that isn't suitable for you..
In PasteFilter(), you trigger another function with a small delay timeout.
In that function, you get the innerHTML contents of the DIV and run a regular expression to remove all tags.
Example:
function PasteFilter()
{
setTimeout('foo()', 200);
}
function foo()
{
var contents = document.getElementById("test").innerHTML;
var new_contents = contents.replace(/(<([^>]+)>)/g, ""); // taken from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
document.getElementById("test").innerHTML = new_contents;
}
The problem with this method is that you lose the caret position...
Hope this helps...
<html>
<head>
<title>Test</title>
</head>
<body>
hello
<script>
var str=document.body.innerHTML;
document.body.innerHTML=str.replace(/hello/g, "hi");</script>
</body>
</html>
In this code hello.html and hello will change hi.html and hi. I don't want to replace href="". How to write regular expression for that ?
The following regex replace wil do what you want:
<script>
var str=document.body.innerHTML;
document.body.innerHTML=str.replace(/(>[^<]*)hello/g, "\1hi");
</script>
But I think it is still fragile, and any solution with regex replaces in .innerHTML will be... Remember that regexes are always a hacky solution when trying to solve problems which involve html/xml parsing.
What do you need this for? Am I guessing correctly when I say that you want to replace all the text content of the document?
In that case, I would suggest getting a list of all content nodes from the DOM (see this question’s accepted answer for two ways to do this, one with jQuery and one without).
Using that, you could then apply your function to update each text node's contents:
var textNodes = getTextNodesIn(el);
for (var i = 0; i < textNodes.length; i += 1) {
textNodes[i].innerHTML = textNodes[i].innerHTML.replace(/hello/g, "hi");
}
This would leave all the HTML attributes unaffected. If you want to adjust those as well (excepting, of course, any href attribute), you could expand the getTextNodes function to include attributes (excepting href attributes) in the returned list of nodes.