how to remove bug character in html using jquery - javascript

I have a bug in my code and i try to remove it using jquery.
Some code:
<div id="content">
s
<div class="breadcrumb">
<h1>Test and etc</h1> etc etc....
I want to use jquery to remove the s (if exist...in some cases not)
I've tried
var cont = $('#content').html();
$('#content').html(cont.replace('/s\s(.*)/','$1'));
Seams that the code above is not working...some sugestions ?

Don't use a regex to remove a textnode by running a replace on the HTML, target the textnode directly
var content = document.getElementById('content'),
child = content.firstChild;
if (child.nodeType === 3) { // if textNode
content.removeChild(child);
}
FIDDLE

You do need to call the code when the DOM is ready. And remove the quotes.
$(document).ready(function(){
var cont = $('#content').html();
$('#content').html(cont.replace(/s\s(.*)/,'$1'));
});
Fiddle : http://jsfiddle.net/anj1x7xe/

I don't understand, why won't you remove it directly from the HTML source?
Is the code automatically generated (aka you didn't manually write that 's' there)? Because if it is, I strongly suggest you correct the bug itself. What you're trying to do is covering up a bug, not fixing it. It's good practice to get to the source of a bug and fix it.
Alas, if you really want to do this: You need to specify when your script is called. Most likely, you want it put into the $(document).ready() event.
$(document).ready(function(){
var cont = $('#content').html();
$('#content').html(cont.replace('/s\s(.*)/','$1'));
});

Related

Replace non-code text on webpage

I searched through a bunch of related questions that help with replacing site innerHTML using JavaScript, but most reply on targetting the ID or Class of the text. However, my can be either inside a span or td tag, possibly elsewhere. I finally was able to gather a few resources to make the following code work:
$("body").children().each(function() {
$(this).html($(this).html().replace(/\$/g,"%"));
});
The problem with the above code is that I randomly see some code artifacts or other issues on the loaded page. I think it has something to do with there being multiple "$" part of the website code and the above script is converting it to %, hence breaking things.using JavaScript or Jquery
Is there any way to modify the code (JavaScript/jQuery) so that it does not affect code elements and only replaces the visible text (i.e. >Here<)?
Thanks!
---Edit---
It looks like the reason I'm getting a conflict with some other code is that of this error "Uncaught TypeError: Cannot read property 'innerText' of undefined". So I'm guessing there are some elements that don't have innerText (even though they don't meet the regex criteria) and it breaks other inline script code.
Is there anything I can add or modify the code with to not try the .replace if it doesn't meet the regex expression or to not replace if it's undefined?
Wholesale regex modifications to the DOM are a little dangerous; it's best to limit your work to only the DOM nodes you're certain you need to check. In this case, you want text nodes only (the visible parts of the document.)
This answer gives a convenient way to select all text nodes contained within a given element. Then you can iterate through that list and replace nodes based on your regex, without having to worry about accidentally modifying the surrounding HTML tags or attributes:
var getTextNodesIn = function(el) {
return $(el)
.find(":not(iframe, script)") // skip <script> and <iframe> tags
.andSelf()
.contents()
.filter(function() {
return this.nodeType == 3; // text nodes only
}
);
};
getTextNodesIn($('#foo')).each(function() {
var txt = $(this).text().trim(); // trimming surrounding whitespace
txt = txt.replace(/^\$\d$/g,"%"); // your regex
$(this).replaceWith(txt);
})
console.log($('#foo').html()); // tags and attributes were not changed
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo"> Some sample data, including bits that a naive regex would trip up on:
foo<span data-attr="$1">bar<i>$1</i>$12</span><div>baz</div>
<p>$2</p>
$3
<div>bat</div>$0
<!-- $1 -->
<script>
// embedded script tag:
console.log("<b>$1</b>"); // won't be replaced
</script>
</div>
I did it solved it slightly differently and test each value against regex before attempting to replace it:
var regEx = new RegExp(/^\$\d$/);
var allElements = document.querySelectorAll("*");
for (var i = 0; i < allElements.length; i++){
var allElementsText = allElements[i].innerText;
var regExTest = regEx.test(allElementsText);
if (regExTest=== true) {
console.log(el[i]);
var newText = allElementsText.replace(regEx, '%');
allElements[i].innerText=newText;
}
}
Does anyone see any potential issues with this?
One issue I found is that it does not work if part of the page refreshes after the page has loaded. Is there any way to have it re-run the script when new content is generated on page?

Grabbing text from a span tag

I have some code for Javascript using jQuery, and I've been wondering how to fix an element of it.
var dataGiven = +$("span.cost-in-usd:first-child").text();
However, the span tag is:
<span class="cost-in-usd" data-se="product-usd-value">42</span>
Is there a way of modifying my code in order for it to recognise data-se?
Yes, use data.
var datase = $('.cost-in-usd').data('se');
Some links;
http://api.jquery.com/jquery.data/
Here's a jsfiddle
The following will return the value of attribute
$('.cost-in-usd').attr('data-se');

Deleting and inserting Code in a DIV via jQuery

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)
If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");
.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);
I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

How can I set the value of a CodeMirror editor using Javascript?

I try to set id4 in the following code:
<div id="id1">
<div id="id2">
<div id="id3">
<textarea id="id4"></textarea>
</div>
</div>
</div>
By using this code:
document.getElementById('id4').value = "...";
And this:
document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";
But nothing works.
UPDATED:
The textarea is replaced by CodeMirror editor. How do I set value to it?
Thanks a lot for the help!
The way to do this has changed slightly since the release of 3.0. It's now something like this:
var textArea = document.getElementById('myScript');
var editor = CodeMirror.fromTextArea(textArea);
editor.getDoc().setValue('var msg = "Hi";');
I like examples. Try this:
CodeMirror.fromTextArea(document.getElementById(id), {
lineNumbers: true
}).setValue("your code here");
As you said, the textarea is replaced by Codemirror. But it is replaced by an element with the class "CodeMirror". You can use querySelector to get the element. The current CodeMirror instance (and its methods) is attached to this element. So you can do:
document.querySelector('.CodeMirror').CodeMirror.setValue('VALUE')
CodeMirror ~4.6.0 you can do this, assuming you have a codemirror object:
var currentValue = myCodeMirrorObject.cm.getValue();
var str = 'some new value';
myCodeMirrorObject.cm.setValue(str);
The code you have should work. The most likely explanation for it failing is that the elements do not exist at the time you run it. If so the solutions are to either:
Move the JS so it appears after the elements have been created (e.g. to just before </body>)
Delay execution of the JS until the elements have been created (e.g. by moving it to a function that you assign as the onload event handler)
This has worked for my (pretty old) version of CodeMirror:
var editor=CodeMirror.fromTextArea('textarea_id');
editor.setCode('your string');

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

Categories

Resources