JS tiny text replace problem - javascript

Under normal circumstances I would simply look this up, but I don't have my JS reference so...
I have this code:
var text = document.createTextNode(alt);
var empty = document.createTextNode("");
desc.appendChild(empty);
desc.appendChild(text);
I need to alter the appendChild to something that will replace the current child value rather than add to it. I've googled for this and come up short for some reason.

Try this:
desc.replaceChild(text, desc.firstChild);

desc.innerHTML = 'some text'; - simplest way i think

Um, how about replaceChild?
desc.replaceChild(text,empty);
This replaces the empty child node with the text child node.

Related

How to fill this textbox? [duplicate]

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
Here's what the function will look like:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
You can simply use:
fieldNameElement.innerHTML = "My new text!";
Updated for everyone reading this in 2013 and later:
This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.
To replace text inside a div element, use Node.textContent, which is provided in all current browsers.
fieldNameElement.textContent = "New text";
function showPanel(fieldName) {
var fieldNameElement = document.getElementById("field_name");
while(fieldNameElement.childNodes.length >= 1) {
fieldNameElement.removeChild(fieldNameElement.firstChild);
}
fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}
The advantages of doing it this way:
It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML
If I were going to use a javascript library, I'd use jQuery, and do this:
$("div#field_name").text(fieldName);
Note that #AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.
I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.
$("field_name").update("New text");
Element.update documentation
$('field_name').innerHTML = 'Your text.';
One of the nifty features of Prototype is that $('field_name') does the same thing as document.getElementById('field_name'). Use it! :-)
John Topley's answer using Prototype's update function is another good solution.
The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR
in IE:-
document.getElementById("field_name").innerText = newText;
in FF:-
document.getElementById("field_name").textContent = newText;
(Actually of FF have the following present in by code)
HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })
HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })
Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.
If you really want us to just continue where you left off, you could do:
if (fieldNameElement)
fieldNameElement.innerHTML = 'some HTML';
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.
http://docs.jquery.com/Manipulation
Makes it as simple as:
$("#field-name").text("Some new text.");
Use innerText if you can't assume structure
- Use Text#data to update existing text
Performance Test
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
fieldNameElement.removeChild(fieldNameElement.firstChild);
var newText = document.createTextNode("New Text");
fieldNameElement.appendChild(newText);
}
Here's an easy jQuery way:
var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
In HTML put this
<div id="field_name">TEXT GOES HERE</div>
In Javascript put this
var fieldNameElement = document.getElementById('field_name');
if (fieldNameElement)
{fieldNameElement.innerHTML = 'some HTML';}

Can't use document.getElementById().innerHTML to rewrite the original html

I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)
var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";
One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.
alert(originaltext);
your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/
var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";
check that you only have one element with the id "cartzone"
A simple and fast way to do this is to concatenate the old value with the new.
document.getElementById('myid').innerHTML += " my new text here"
this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times.
I had the same problems in the past.
you have tow options:
check the rest of your code (validate)
use jQuery - I don't know how, but it works every time.

jQuery how to insert <br/> tag after every Semicolon

I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.
I have something like this...
HTML
<div class='test'>
color:red;background-color:black;
</div>​
jQuery
var test = $('.test').text();
var result = test.match(/;/g);
alert(result);​
And I have tried..
var test = $('.test').text();
var result = test.match(/;/g);
result.each(function(){
$('<br/>').insertAfter(';');
});
alert(result);​
Also I have started a fiddle here.. Which basically just returns the matched character...
http://jsfiddle.net/krishollenbeck/zW3mj/9/
That is the only part I have been able to get to work so far.
I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...
try it like this
var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');
$('.test').html(result);​
http://jsfiddle.net/Sg5BB/
You can use a normal javascript .replace() method this way:
​$(document)​.ready(function(){
$(".test").html($(".test").html().replace(/;/g, ";<br />"));
});​
Fiddle: http://jsfiddle.net/SPBTp/4/
Use This CODE
var test = $('.test').text();
var result = test.split(';').join(';<br />')
http://jsfiddle.net/FmBpF/
You can't use jQuery selectors on text, it only works on elements.
Get the text, just replace each ; with ;<br/>, and put it back.
$('.test').html($('.test').text().replace(/;/g, ';<br/>'));
Try something like this :
var test = $('.test').text();
var result = test.replace(/;/g,";");
$('.test').html(result);
​
That should work if you stick it into your jfiddle.

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

JQUERY FIND:FIRST not finding the first Paragraph?

Goal, is to extract the content for the CKEDITOR Text Editor, and then only obtain the FIRST paragraph. For some reason the bellow isn't working... Ideas?
Given the following JavaScript:
var newTitle = CKEDITOR.instances.meeting_notes.getData();
newTitle = $(newTitle).find("p:first").text();
It doesn't work because find() searches the descendants and your paragraph must be at the top level of the HTML you're searching.
For example:
alert($("<p id='one'>one</p><p id='two'>two</p>").find("p:first").attr("id"));
returns "undefined" whereas:
alert($("<p id='one'>one</p><p id='two'>two</p>").filter("p:first").attr("id"));
will output "one".
So you could use filter() if you know it's at the top level (possibly falling back to find()). Alternatively you could wrap the whole lot up in a dummy element:
alert($("<div>" + html + "</div>").find("p:first").text());
Edit: My advice? Use:
newtitle = $(newtitle).filter("p:first").text();
I am not sure if works for you, but just try putting a space before :first,
for some reasons i can't explain this works as far my experience is concerned:
The new selector for find would now be, find("p: first")
var newTitle = CKEDITOR.instances.meeting_notes.getData();
newTitle = $(newTitle).find("p :first").text();
BTW can you post some sample values of the newTitle, just curious of what it looks like!
This is completely untested, but assuming that what getData returns is a string of HTML, try this:
newTitle=$("<div>").html(newTitle).find("p:first").text();

Categories