How can i append pure string into div? - javascript

So this is the requirement. The user can insert tags inside text_field input.
and i got the data from the db like this.
var input = "test<br/><iframe src='http://stackoverflow.com/'>" ;
I ONLY want to append this to PURE string. not tags
but if i append it runs like a tag.
the result i want is just printing
test<br/><iframe src='http://stackoverflow.com/'>
as a pure string.
Any good solution?
html,
<div id="i_want_only_string">
</div>
javascript,
$(function(){
var input = "test<br/><iframe src='http://stackoverflow.com/'>" ;
$("#i_want_only_string").append(input);
});
DEMO

Try appending a TextNode - create it using document.createTextNode()
$(function () {
var input = "test<br/><iframe src='http://stackoverflow.com/'>";
$("#i_want_only_string").append(document.createTextNode(input));
});
Demo: Fiddle
As #BillCriswell noted below if the container #i_want_only_string is empty, you can use .text() like
$(function () {
var input = "test<br/><iframe src='http://stackoverflow.com/'>";
$("#i_want_only_string").text(input);
});
Demo: Fiddle

You can append your container with the contents of a new tag that has your input text as its innerText
$(function () {
var input = "test<br/><iframe src='http://stackoverflow.com/'>";
$("#i_want_only_string").append($('<span>').text(input).contents());
});
DEMO

Related

Using Javascript to hide text shown on currency switch

I'd like to use Javascript (on page load) to remove the wording 'Choose a currency to display the price:'.
Leaving just the currency icons in the box (Div id = currency-switch).
How can I do this?
Page url: http://www.workbooks.com/pricing-page
Image example:
You can remove this text with for example:
window.onload = function(){
var el = document.getElementById("currency-switch");
var child = el.childNodes[0];
el.removeChild(child);
};
If you want to keep it stupid simple just add an span around the text and give it an id like "currency_text".
Then you only need this code:
var elem = document.getElementByid("currency_text");
elem.remove();
Try
$(document).ready(function() {
var currencyDiv = $('#currency-switch');
currencyDiv.innerHTML(currencyDiv.innerHTML().replace("Choose a currency to display the price:", ""));
}
This will remove the text as soon as the DOM is ready.
Please see below which will just remove the text:
This will trigger on page load
<script>
// self executing function here
(function() {
var selected_div = document.getElementById('currency-switch');
var text_to_change = selected_div.childNodes[0];
text_to_change.nodeValue = '';
})();
</script>
Since it's a text node, you could do the following in jQuery. This will be triggered on DOM ready.
$(function() {
jQuery("#currency-switch").contents()
.filter(function() {
return this.nodeType === 3;
}).remove();
});
You can use this code:
var requiredContent = document.getElementById('currency-switch').innerHTML.split(':')[1];
document.getElementById('currency-switch').innerHTML = requiredContent;
See it working here: https://jsfiddle.net/eg4hpg4z/
However, it is not very clean, but should work, if you cant directly modify the html.
A better solution would be to modify your code to move the text content within a span and show hide the text like so:
HTML:
<div id="currency-switch">
<span class="currency-label">Choose a currency to display the price: </span>
<span class="gb-background"><span class="GB"> £ </span></span><span class="es-background"><span class="ES"> € </span></span><span class="au-background"><span class="AU"> $ </span></span></div>
Javascript:
document.getElementsByClassName('currency-label')[0].style.display = 'none';

Create "title" attribute using the text inside <a> tag?

Is it possible to take the text inside of an <a> tag and add it to title attribute of that tag using JavaScript?
For example:
Hello
I want the text "hello" to be the title attribute to the <a> tag. Like this:
Hello
Can this be done with JavaScript? Any help or direction would be appreciated.
In javascript, as requested:
var anchors = document.getElementsByTagName('a');
for(i = 0;i < anchors.length; i++) {
anchors[i].title = anchors[i].textContent;
}
http://jsfiddle.net/spencerooni/z97rc/
If you have an ID for the specific tag (e.g. ...):
$('#atag').attr('title', $('#atag').text());
or if you'd like to do this for all a tags:
$('a').each(
function() {
$(this).attr('title', $(this).text());
}
);
DEMO
$('a').each(function() {
var $this = $(this); /* slight optimisation over using $(this) twice */
$this.attr('title',$this.text());
});
In the most simple jQuery form:
$('a').attr('title', function(){ return $(this).text() })
jsFiddle example

How to get div text also with it's input's values

I was wondering how to obtain the text inside a given div, with also the input's values as text.
<div id="example">This is a <input type="text" value="right"/> test.</div>
If I just try to get text like this with jQuery :
$("#example").text();
The result would be This is a test. and I'd want : This is a right test.
The number of input would be unknow. As well as the order of the elements...
EDIT :
I finally resolved my own problem :
var finalText="";
$("#example").contents().filter(function() {
if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
return finalText
})
The living example
But #Jonathan Lonowski answer is more clear and simpler than mine !
Here is a quick plugin that will do this for you:
$(document).ready(function() {
$.fn.extend({
getContentText: function() {
var t = '';
this.contents().each(function(i,c) {
var method = $(c).is("input") ? "val" : "text";
t += $(c)[method]();
});
return t;
}
});
alert($("#example").getContentText());
});
Try it out here:
http://jsfiddle.net/wQpHM/
You might try cloning so you can replaceWith the inputs with their values. Then grab the text as you were:
var clone = $('#example').clone();
clone.find(':input').replaceWith(function () {
return $(this).val();
});
alert(clone.text());
You can loop though all children of the <div> and replace then with their values. Something like this:
$.fn.allText = function(){
var $this = this.clone();
$this.children().each(function(){
$(this, $this).replaceWith(this.value);
});
return $this.text();
};
alert($('#example').allText());
Demo: http://jsfiddle.net/4mGmH/
get html and strip html tags
$('#example')[0].innerHTML.replace(/(<([^>]+)>)/ig, '').replace(/(\s+)/g, ' ')
Using innerText
document.getElementbyId('example').innerText;
To get HTML tags:-
document.getElementbyId('example').innerHTML;
Refer this URL element.innerHTML

get the text content from a contenteditable div through javascript

I want retrieve the text content from a contentEditable div through javascript. What are the options of doing this? I've tried innerHTML but it doesn't work.
Why not use textContent for this:
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
http://jsfiddle.net/E4W8y/1/
Unfortunately, I've found that innerText is the only way to preserve newlines in contenteditable dom nodes. What I'm doing (tested only in chrome at the moment) is this:
var innerText = editableDiv.innerText // using innerText here because it preserves newlines
if(innerText[innerText.length-1] === '\n')
innerText = innerText.slice(0,-1) // get rid of weird extra newline
return innerText
lblMailContent is the id of editable field.
var details= document.getElementById("lblMailContent").innerHTML;
Put this code in clientClick. It worked well for me.
use jQuery and do
var content = $('#my-contenteditable-div').html();
also look up these links:
http://west-wind.com/Weblog/posts/778165.aspx
Extracting text from a contentEditable div
I solved it this way, because i need html-input:
message = $('<div>').html(
$('#area').html()
.replace(/<(div|p|br)[^<]*?>/g, '<br />')
.replace(/<([(i|a|b|u)^>]+)>(.*?)<\/\1>/gim,
function(v) { return '' + escape(v) + ''; })
).text();
Allows the tags A, B, I, U and replaces Divs and Ps with BRs
Using text content, working fine in most of the cases
Working Example: jsfiddle(verified in Safari)
Use this:
function textFromDiv(selector) {
const element = document.querySelector(selector);
const text = element.html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
return text;
}```
Here's my spin at it...
input = document.getElementsByTagName("div")[0];
input.onkeyup = function(){
text = "";
for(i=0; i<input.childNodes.length; i++){
text += input.childNodes[i].textContent + "\n";
}
text = text.trim();
console.log(text);
}
Vanilla JS solution
html:
<div
contenteditable="true"
onkeyup="myFunction(this, event)"
></div>
js:
function myFunction(self, event){
console.log(self.innerText)
console.log(event)
}

Creating links for elements with a particular class with jQuery

How can I wrap every element belonging to a particular class with a link that is built from the text inside the div? What I mean is that I would like to turn:
<foo class="my-class>sometext</foo>
into
<a href="path/sometext" ><foo class="my-class>sometext</foo></a>
Url encoding characters would also be nice, but can be ignored for now if necessary.
EDIT: Just to clarify, the path depends on the text within the element
Use jQuery.wrap() for the simple case:
$(".my-class").wrap("<a href='path/sometext'></a>");
To process text inside:
$(".my-class").each(function() {
var txt = $(this).text();
var link = $("<a></a>").attr("href", "path/" + txt);
$(this).wrap(link[0]);
});
$(".my-class").each(function(){
var thisText = $(this).text();
$(this).wrap("<a></a>").attr("href","path/"+thisText);
});
you can wrap them inside anchor element like this:
$(document).ready(function(){
$(".my-class").each(function(){
var hr="path/"+$(this).text();
$(this).wrap("<a href='"+hr+"'></a>");
});
});
if you are opening links in same page itself then easier way than modifying dom to wrap elements inside anchor is to define css for the elements so that they look like links then handle click event:
$(".my-class").click(function(){
window.location.href="path/"+$(this).text();
});
$("foo.my-class").each(function(){
var foo = $(this);
foo.wrap("<a href='path/" + foo.Text() +"'>");
});
This ought to do it:
$('foo.my-class').each(function() {
var element = $(this);
var text = element.html(); // or .text() or .val()
element.wrap('');
});

Categories