Find Text from content then hide - javascript

I am trying hide specific Text elements from content by jquery.
HTML:
<div id="name">
Trying hide specific Text elements from content.
</div>
I want this:
<div id="name">
Trying hide <p style="display: none;">specific</p> Text elements from content.
</div>
Or any others simple solution by jquery?

somthing simple like
var nameText = $('#name').text();
var newText = nameText.replace('specific','<p style="display:none">specific</p>');
$('#name').html(newText) // use html() here, not text()

add an id to your p tag and you can hide it by jquery like
$( document ).ready(function() {
$("#p-id").hide();
});

I make function for you
function hideIt(elem, exclude){
var text = elem[0].innerText;
var exculude = exclude;
var match = text.match(exclude);
if(match === null){
console.log('no match founded')
}
else{
for(var i =0 ; i<match.length; i++){
elem[0].innerText = text.replace(match[i],"")
}
}
}
hideIt($('#name'),'specific');
place 1rst param your elem with jquery selector and on 2nd parm the string want to kill
https://jsfiddle.net/xps4553m/5/ for you

Related

javascript: deleting tags of a selected element in a text

I put a tag to a selected element in my textarea and every tag take an id. And I store the element an a table.
But, I want to delete some tags(I have to type of tag "ref" et "point"). And I try this function but, it doesn't work:
function deleteTag(textField, tag)
{
var scrollTop = textField.scrollTop; //For the scroll of the text
var start = textField.selectionStart; //beginning of the selected text
var end = textField.selectionEnd; //End of the selected text
var modif=textField.value.substring(start,end); //The text to modify
// Remove the tag
if(modif.match('[^<]'+tag+'id="(\\d+)">') && modif.match('</'+tag+'[>$]'))
{
var regex;
if(tag=="ref")
{
regex=new RegExp('<'+tag+' id="(\\d+)">');
var opt=modif.match(regex)[1];
document.getElementById("refList").remove(opt-1);
}
regex=new RegExp('<'+tag+'[^>]+>');
modif=modif.replace(regex, "");
modif=modif.replace('</'+tag+'>', "");
}
textField.value=textSup+modif+textInf; //We modify the text inside the text area
textField.scrollTop=scrollTop;
}
And the button have this code:
<button onclick="deleteTag(textAreaId, 'ref')"> Effacer
By the way I'm beginner in javascript
if(modif.match('[^<]'+tag+'id="(\\d+)">') && modif.match('</'+tag+'[>$]'))
maybe you need an extra space in the regex:
if(modif.match('[^<]'+tag+' id="(\\d+)">') && modif.match('</'+tag+'[>$]'))

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';

replacing html tag inside textarea with text

code :
<script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var $this = $("#Test_txtarea");
var txtval = $this.val();
$this.find("img").each(function () {
var imgbytes = $(this).attr("name"); // extract bytes from selected img src
$(this).replaceWith(imgbytes);
});
$("#NewVal").html(txtval);
});
</script>
html
<textarea ID="Test_txtarea" >Hi <img src='test.png' name='test' > kifak <img src='test2.png' name='test1' > Mnih <img src='test3.png' name='test3' ></textarea>
<span id="NewVal" ></span>
what i am trying to do is basically trying to replace each img tag by it's name so the final textarea value will be like this : Hi test kifak test1 Mnih test3
this is the jsfiddle : http://jsfiddle.net/Ga7bJ/2/
the .find("img") always return 0 as length.how can i fix this code ?
Though it is not complete answer or at least not going to be "Copy paste" answer, there is few things you need to do here:
The content of Textarea is VAL of it and not InnerHTML. So, you have to pick that content as value and than create a hidden div and put it as HTML. Once you did it, you can now find the HTML tags in it using find rather easily.
Once you find tag you can find the name using attr() function
Once you have name, than you again go back to val() of textarea, and do regex replace or using HTML you can replace as well I guess, but not sure.
Look at this jsFiddle. What is does is:
It gets the value from your Test_txtarea and sets that as the html of a hidden div.
The hidden div wil render the images within the textarea.
After they have been rendered, I find these images,
- get the source,
- remove all characters after the .
- replace the entire html of the image with the src.
After all that has been done you are left with a div with the value you wanted.
All what is done next is the html from the div is copied to the value of your textarea.
function replaceImageWithSrc(value){
var div = $("#invisible");
div.html(value);
var images = div.find("img");
images.each(function(index){
var src = $(this).attr("src").split(".")[0];
this.outerHTML = src;
});
return div.html();
}
$(document).ready(function () {
var txtArea = $("#Test_txtarea");
var txtval = txtArea.val();
txtval = replaceImageWithSrc(txtval);
txtArea.val(txtval);
});
The following code works for me. Basically, I get the value of the text area and append it to an off-screen div. Now that I have valid markup nesting, I can iterate the child-nodes as normal.
function byId(e){return document.getElementById(e)}
function newEl(t){return document.createElement(t)}
function test()
{
var div = newEl('div');
div.innerHTML = byId('Test_txtarea').value;
var msg = '';
var i, n = div.childNodes.length;
for (i=0; i<n; i++)
{
if (div.childNodes[i].nodeName == "IMG")
msg += div.childNodes[i].name;
else if (div.childNodes[i].nodeName == "#text")
msg += div.childNodes[i].data;
}
byId('NewVal').innerHTML = msg;
}

Inserting element just before selected text

I'd like to implement such a function on a web page: When called, it checks whether there are some text selection(often displayed as inverted colored text) on the page, if yes, insert an element <img src="my.png"/> just before the first word of the selection.
Pure JavaScript or jQuery code are both welcome, jQuery preferable. Thank you.
I can propose you this solution :
$('#butt').click(function(){
var sel = window.getSelection();
if (sel.toString().length>0) {
var key = sel.anchorNode.compareDocumentPosition(sel.focusNode) & Node.DOCUMENT_POSITION_PRECEDING
? 'focus' : 'anchor';
var $elem = $(sel[key+'Node']), txt = $elem.text(), offset = sel[key+'Offset'];
var $f = $(document.createTextNode(txt.slice(0, offset)));
$elem.replaceWith($f);
$(document.createTextNode(txt.slice(offset))).insertAfter($f);
$('<img src=http://dystroy.org/flore/icon.png>').insertAfter($f);
}
});
Demonstration
<div id="test">
<span class="spanthatcontainstext">test</span>
</div>
$(function(){
var checkfortext = $('.spanthatcontainstext').length;
if(checkfortext){
$(checkfortext).prepend('<img src="" />');
} else {
//do something if there is no text
}
});

How to append an element to a div which is without id

I want to use javascript to add a link inside a div, this div doesn't have id , it does has a class though:
<div class="details">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
How to add a link inside the "details" div and above the "delete" link?
The link I want to add is:
Edit
go for jquery, it's simple and clean.
you can grab any element with a particular class say
<div class="className" ></div>
like this
<script>
$('.className');
</script>
now you want to append someother element just before the anchor having delete class, well than you can do this:
$('.delete').before('Edit');
there are other methods also to append an element inside any other element or dom
1. $('.className').append('<div> i will be appended at the bottom of this element</div>');
2. $('.className').after('<div> i will be appended right after this element</div>');
for using jquery, you will need its api, directly use this link in your page or, download the latest jQuery api and use it.
its simpler and easier.
function hasClass(element, className) {
var s = ' ' + element.className + ' ';
return s.indexOf(' ' + className + ' ') !== -1;
}
/**
* from: http://www.dustindiaz.com/getelementsbyclass
*/
function $class(className, context, tag) {
var classElements = [],
context = context || document,
tag = tag || '*';
var els = context.getElementsByTagName(tag);
for (var i = 0, ele; ele = els[i]; i++) {
if (hasClass(ele, className)) {
classElements.push(ele);
}
}
return classElements;
}
then use the $class('delete') to locate the elements, and then prepend new elements
It's always best to search by id, it is most efficient. However if it comes to it, you may find elements by class or tag name as well.
I recommend using jQuery, and changing the existing tag you have:
$('a').attr('href', '#edit_link').text('Edit').removeClass('delete').addClass('edit');
If it is not possible to add an id to the element you're finding, find an element somewhere higher in the tree that has an id, and go from there:
$('#someHigherId > div > a')...
You could use jQuery:
$('div.details a.delete').before('Edit');
You can do it using javascript like this
<script type="text/javascript">
function addtext(what){
if (document.createTextNode){
var link = document.createElement('a');
link.setAttribute('href', '#edit_link');
link.setAttribute('id', 'edit');
link.setAttribute('class', 'edit');
document.getElementsByTagName("div")[0].appendChild(link)
document.getElementById("edit").innerHTML = what;
}
}
</script>
<div class="details" id="mydiv" onClick="addtext('Edit')">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
Using pure JavaScript:
var div = document.getElementsByClassName('details')[0],
deleteLink = div.getElementsByClassName('delete')[0],
editLink = document.createElement('a');
editLink.textContent = 'Edit';
editLink.className = 'edit';
editLink.href = '#edit_link';
div.insertBefore(editLink, deleteLink);

Categories