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
Related
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';
I have many hyperlinks with a onclick function which have differents values on this way:
<a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'bikes'});">bikes whatever</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'motorcycles'});">another motor</a>
Now when this element is clicked I need to get the values of that array, example: "cars", or "bikes" or "motorcycles".
Don't suggest to get them from the Utils.decideOffer function because I need to get them without edit that file/function. This is how I intend to extract it.
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var optionSelectedValue = ??? ;
}
});
I was thinking on use Regex so can you please help me on the Regex to use on this case?, or if you have another good idea to achieve this it is also welcome!
Try split() like :
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var optionSelectedValue = onclickValue.split(":")[1].split("}")[0];
}
});
it will return the 'cars' or 'bikes' or 'motorcycles' including the quotes
See JSFIDDLE
... or to get the value without quotes as suggested :
optionSelectedValue = onclickValue.split(":")[1].split("}")[0].split("'")[1];
See updated JSFIDDLE
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var re = /(?!: ')+(\w)+(?='})/;
var found = onclickValue.match(re);
var optionSelectedValue = found[0] ;
alert(optionSelectedValue);
}
});
Demo: http://jsfiddle.net/wpjh1ma7/
I am trying to find all elements with an onclick attribute and append ";toggle()"
var originalAttribute = $('[onclick]').attr('onclick');
$('[onclick]').attr('onclick', originalAttribute + ';toggle()');
There is something obviously wrong, but what?
$('[onclick]').attr('onclick'); will return the value for the first matching element.
You need to do this for each element. Try this:
$('[onclick]').each(function() {
var $this = $(this);
var originalAttribute = $this.attr('onclick');
$this.attr('onclick', originalAttribute + ';toggle()');
});
Here's a fiddle.
I think you are looking for something like this:
EDIT:
$('[onclick!=""]').each(function(){
$(this).attr('onclick', $(this).attr('onclick') + ';toggle()');
});
I want to read an html tag which has formatted text. For example
<p id="strike" onMouseOver="getP()><b>Hello</b></p> // paragraph Tag with formatted text
if i am calling a function,
function getP()
{
var val=document.getElementById('strike').value;
alert(val);
}
am getting undefined in alert, how to get the exact bold formatted text or bold tag with text....Please help me out in this
var val=document.getElementById('strike').innerHTML;
alert(val);
Use alert(document.getElementById('strike').innerHTML);
p does not have value property. You need to get the first childNode which is b, and access the innerHTML property.
var val=document.getElementById('strike').childNodes[0].innerHTML;
I'd suggest using:
function getP() {
var el = document.getElementById('strike').getElementsByTagName('b')[0],
text = el.textContent ? el.textContent : el.innerText;
alert(text);
}
JS Fiddle demo.
Updated the above, and generalised some:
<script type="text/javascript">
function getP(el,tagtype) {
if (!el || !tagtype) {
return false;
}
else {
var textFrom = el
.getElementsByTagName(tagtype)[0],
text = textFrom.textContent ? textFrom.textContent : textFrom.innerText;
console.log(text);
}
}
</script>
<p id="strike" onMouseOver="getP(this, 'b')"><b>Hello</b></p>
JS Fiddle demo.
var val=document.getElementById('strike').innerHTML;
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)
}