javascript replace text after the page has loaded - javascript

I want to remove/hide a piece of text that loads on my page.
The element doesn't have an id to relate to so I want to use a text-specific method.
Let's say the text is:"remove this line of text".
The html looks like this:
<div class="aClassName">
<p>
<strong>remove this line of text</strong>
... the rest of the content.
</p>
I have tried the following:
jQuery(document).ready(function($){
document.body.innerHTML = document.body.innerHTML.replace('remove this line of text', '');
});
Didn't work. So I tried this:
jQuery(document).ready(function($){
$("body").children().each(function () {
$(this).html( $(this).html().replace(/remove this line of text/g,"") );
});
});
Didn't work. The idea is that after the page is loaded it removes the line.It doesn't produces any errors as well. Not even in the firebug.
Anyone?

Target Elements Based On Their Content
You could accomplish this using the :contains() pseudoselector in jQuery that would allow you to target certain elements based on their contents :
$(function(){
// This will remove any strong elements that contain "remove this line of text"
$('strong:contains("remove this line of text")').remove();
});
You can see a working example of this here.
Broader Approach (Just Targets Elements Based On Selectors)
If you wanted a more simply target it by a more general selector (i.e. any <strong> tags that appear beneath a class called aClassName :
$('.aClassName strong').remove();
You can see an example of this approach here.

I guess you can use find() and text(), i.e.:
$('.aClassName').find('strong').text("123");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aClassName">
<p>
<strong>remove this line of text</strong>
... the rest of the content.
</p>
Or simply:
$('strong:contains("remove this line of text")').text("New text");
Update:
After analyzing the link supplied on the comments, you can use the following:
$('.payment_method_mollie_wc_gateway_ideal').find('strong').text("");

Related

Regex to extract particular attribute and innerHTML of a div inside contentEditable

Background
I am creating a #Name Tagging system for my webpage. and I've succeeded in finding names on keystroke and replace the content with equivalent div class='tag' data-id='User-id'>Name</div>(at least for displaying). Now before submitting those contents from contentEditable div. I modify them in a textarea (which is usually hidden).
Working
As soon as .keyup event occurs on contentEditable all the contents of contentEditable are processed by function MakeItForWeb(contentEditable). Which then Manipulates the contents of textarea which will be processed by server side php script. that php script will strip all the tags and then store data in DB. so before submitting I try to replace all the .tag div with following format of data:
#["id":"User-id","Tag":"User-Name"];
In <textarea>, I have created a regular expression in javascript to achieve the task. and it is working fine, when there is single .tag in single line, You can see it Here.
Problem
When More than 1 .tag occurs in a single line then My regex fails to recognize all of them correctly, and recognize only last of them. And thus whole tagging system crashes, You can see it Here. May be My approach is wrong. Can Experts here help me out please? any suggestion is welcome.
My Efforts(Code)
JavaScript + JQuery:
$(document).ready(function(){
$("body").attr("spellcheck","false");
$("#tarea").keyup(function(e){ // Process KeyUp Event
/* Code to find Names on #N..and create a tag is omitted purposefully as it is working fine */
// Make each tag Un-editable, So that User cant change it
$(".tag").each(function(){
$(this).attr("contentEditable","false");
});
//Manipulate the textarea with equivalent value
MakeItForWeb(this);
}).focus(function(){
//Manipulate the textarea with equivalent value from contentEditable
MakeItForWeb(this);
});
$("#tarea").trigger("keyup"); // Trigger keyUp event as soon as DOM ready.
});
function MakeItForWeb(x){
var htm=$(x).html(); // Contents of contentEditable
htm=htm.split("<br>").join("\n"); // Replace <br> with \n character
htm=htm.split(" ").join(" ");
htm=htm.trim(); // Trim contents
/* Here is My regex which does the mentioned task */
htm=htm.replace(/<div(.*) data-id=\"(.*)\" (.*)>(.*)<\/div>/g,"#['id':'$2','tag':'$4'];");
document.getElementById("opc").value=htm; // <textarea> = ContentEditable processed.
}
Note the Line:
htm=htm.replace(/<div(.*) data-id=\"(.*)\" (.*)>(.*)<\/div>/g,"#['id':'$2','tag':'$4'];");
// This is My Regex.
// where var htm=contentEditable.innerHTML;
HTML:
<div id="tarea" contentEditable="true" class="tarea" autocorrect="false" spellCheck="off">
Hello Says! <div class="tag" data-id="1005">Vedant Terkar</div> , <br />To all <div class="tag" data-id="1006">SO Users</div> :-).
</div>
<!-- This textarea is Usually Hidden -->
<textarea id="opc" rows="5" cols="97">
</textarea>
css is irrelevant to problem, so not posting it.
Hope experts here will help me out. Thanks in advance :-) !
Regex:
<div\b.*?\bdata-id=\"([^"]*)\">([^<]*).*?\/>([^<]*)<div\b.*?\bdata-id=\"([^"]*)\">([^<]*).*
Replacement string:
#['id':'$1','tag':'$2']; , $3#['id':'$4','tag':'$5'];
DEMO
Get the matched group from index 1 and 2. I used Lazy way.
<div class="tag" data-id=\"([^\"]*?)\">([^<>]*?)<\/div>
here is online DEMO
Try this one to get the "Hello Says!" and "To all" as well in 3 catapulting groups.
>\s*([^<>]*)<div class="tag" data-id=\"([^\"]*?)\">([^<>]*?)<\/div>
here is online DEMO

Overwrite a class via JavaScript

I want to overwrite some text defined by class=cc-product-infolink and it is defined by the CMS, so i have to change the text in this class via JS. It is my first time to use it, so i have wrote a little script, but it doesn't work. Why?
I would like to change the text "inkl. MwSt, zzgl. Versandkosten " in "inkl. MwSt, Versandkosten gemäß Angaben". And the JS-Code must be work in the head, because there is no possibility to put it into the body.
Here is my HTML Code:
<div class="cc-product-infolink">
<a class="cc-no-clickable-arrow" href="/j/shop/info/m/me6f40c3b0bd58b35" rel="nofollow">inkl. MwSt, zzgl. Versandkosten</a>
</div>
My JS-Code
<script type="text/javascript">
//<![CDATA[
var versand = document.getElementsByClassName('cc-product-infolink')[0];
versand.getElementsByTagName('a')[0].textContent += ' gemäß Angaben';
//]]>
</script>
and it should work here: http://www.wonnemond.de/taschen/karl/#cc-m-product-8254989095
Maybe somebody can help me.
var versand = document.getElementsByClassName('cc-product-infolink')[0];
versand.getElementsByTagName('a')[0].textContent += ' gemäß Angaben';
Some notes:
id and class are not the same. As the name implies, getElementById retrieves elements by their id attribute. Your element only has class, so getElementsByClassName is what you need. I guess you cannot change the HTML.
textContent is used to set/get
the text content of a DOM element. Old IEs (IE8 and older) use
innerText instead.
firstChild does not work because the link is not the first child of that div. There is a text node containing a newline and some indentation before the link. Using getElementsByTagName you can solve this problem though.
And a jsFiddle Demo.

Preserve html characters within google-prettified pre element?

I'm attempted to include syntax highlighting into my Tumblr blog by means of google-prettify and some jQuery.
Google-prettify requires the <pre> element to have a class of prettyprint in order for it to highlight the syntax, but since I'm using markdown to create my Tumblr posts, I can't add a class to my <pre> elements.
My solution is to use this jQuery snippet to append the prettyprint class to the <pre> element:
<script type='text/javascript'>
$(document).ready(function() {
$('pre').addClass('prettyprint');
prettyPrint();
});
</script>
This is working fine, but I'd like to be able to copy and paste the code that I want to show on my Tumblr, instead of converting all < to < and > to > every time I want to post a code snippet.
Using jQuery, I'd like to replace all the < and > with their corresponding html code, but only within the pre element. This however, might have some problems, as it would need to replace all of those before the code is prettified.
Could I append the new class, replace the tags, and then call prettyPrint(); to intialize everything? Or should I just change the html characters into htmlentities by hand before posting the code?
Little update:
This script works with changing the < and >, except with <body>,<html>, and <head>...
<script type='text/javascript'>
$(function() {
var $pre = $('pre');
$pre.html($pre.html().replace(/</g, 'f').replace(/>/g, 'l'));
});
</script>
<pre>
<html></html>
<body></body>
<head><head>
<i></i>
</pre>
Note: I used f as the replacement just to test the code.
If you first replace all the ampersands with entities, and then the less than signs, you can use the returned string as a text-node in a <pre>, or any block container with its white-space set to 'pre'.
function stripX(str){
return str.replace(/\&(?!(\w+;))/g, '&').replace(/</g, '<');
}

extracting text from html file

I'm trying to get nodes containing text from html file using Javascript and jQuery.
if I have a node like
`
<div>txt0
<span>txt1</span>
txt2
</div>
How can I select elements that meets this criteria??
Meaning, I need to retrieve thedivand thespan` , and it would be even better to know location of the text.
I'm trying to get the text to replace it with images in a later function.
I tried this
`
$('*').each(function(indx, elm){
var txt = $(elm).text();
// my code to replace text with images here
});
`
but it does not get the required results.. it does all the parsing in the first element, and changes the html totally.
I don't know exactly what you're trying to solve, but perhaps you can be a bit more specific with your selector?
$("div span").text(); // returns 'txt1'
$("div").text(); // returns 'txt0txt1txt2'
By adding ids and/or classes to your html, you can be very specific:
<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div>
...
// returns all spans with class
// "middlename" inside divs with class "name"
$("div.name span.middlename").text();
// returns the first span with class
// "middlename" inside the fourth div
// with class "name"
$("div.name[3] span.middlename[0]").text();
JQuery has pretty good documentation of these selectors.
If this doesn't help, consider explaining the problem you're trying to solve.
Your markup structure is a bit uneasy. Consider changing to something like this
<div>
<span>txt0</span>
<span>txt1</span>
<span>txt2</span>
</div>
Then using jQuery
$("div span").each(function(k,v) {
$(this).html("<img src=\""+v+".jpg\" />"); //replace with the image
});

Write inside text area with Javascript

I am trying to write something in text area when I click on a link.
function writeText(txt){
document.getElementById("writeArea").innerHTML = txt;
}
I would like to pass html tag in place of txt as parameter to this function so that I can get image, link etc inside text area. Is it possible in Javascript? || JQuery will be good?
Pre-thanks.
Or if jquery tag was there for a reason:
$('#writeArea').val(txt);
You should use value:
document.getElementById("writeArea").value = txt;
If you want to render some images and anchor tags on the screen then don't use a textarea. Use any other container like <div>, <span>, <p> etc.
$("#yourelementid").html(yourtext);
will put the text (in your case HTML) inside the element with id yourelementid
HTML
<p id="para1"></p>
jQuery
var txt = "<a href='http://www.google.com'>Google</a>";
$("#para1").html(txt);
See a working sample
You can easily do it in jQuery if you just want to set the text of a textarea:
$("#yourid").val("hello");
See it working: http://jsfiddle.net/quQqH/
If you're looking to have HTML in it then it needs to be a container element (such as a div).
// Html
<div id="yourid"></div>
//JavaScript
$("#yourid").html('My link');
Otherwise, another option is to have a Rich Text Editor (like Yahoo Editor) so that it renders the HTML that's in the textarea input - this will make it user editable. This is slightly more complicated, as you'll need to include the correct files to make the editor work. Then just do something like the following:
var myEditor = new YAHOO.widget.SimpleEditor('yourid', {
height: '200px',
width: '350px',
toolbar: 0 // Hides the toolbar
});
myEditor.render();
$("#yourid").val("Click for <a href='http://yahoo.com'>Yahoo</a>");
You can see this working: http://jsfiddle.net/quQqH/1/. In this case, I've removed the toolbar by setting it to 0 but it is customisable to show different buttons, etc. Just remove that line to display the default toolbar.
just give like this
$("#ID").val("<img src='images/logo.png' />");
If you want to write long text in the textarea, you can use this way:
HTML
<textarea id="theId"></textarea>
jQuery
var a = 'Test textarea content. Google" ';
$("#theId").val(a);
JS FIDDLE

Categories

Resources