Covert jQuery to javascript - javascript

This is my code please covert my jQuery into javascript.
Convert in javascript
$(".wrapper td li>span").text(function () {
return $(this).text().replace(".", "");
});

Using querySelectorAll and textContent
document.querySelectorAll('span').forEach(function(el) {
el.textContent = el.textContent.replace(/\./g, '')
});
<span>1. abc</span><br/>
<span>2. def</span>

Finally I got a proper answer to convert jQuery to JavaScript with and issues on enterprise mode of internet explorer
var spans=document.body.querySelectorAll('.wrapper td li>span')
for (i = 0; i < spans.length; i++) {
spans[i].innerText = spans[i].innerText.replace(/\./g, '')
}

Related

jQuery attribute "[something*=something]" selector in pure JavaScript

I am curious if pure javascript can replace this jQuery selector for IE7 and greater..
Do people simply change the markup and select using a class or is their away of selecting this using pure javascript
<h1 rel="xxxexternalxxx">Attribute Contains</h1>
var arrinput = $('[rel*="external"])
Any help would be much appreciated, thank you in advance
You can use getElementsByAttribute, then loop and filter:
var rels = getElementsByAttribute('rel');
var attr = 'external';
var result = [];
for (var i=0; i<rels.length; i++) {
if (rels[i].getAttribute('rel').indexOf(attr) > -1) {
result.push(rels[i]);
}
}

Hide numbers with javascript, without using jQuery

I have the following fiddle.
When you click the Hide button the numbers 2, 3 and 1 are hidden. All works great using this Jquery code:
$( "#hide" ).click(function() {
$('span').each(function(){
if($(this).text().match(/^([1-9])$/))$(this).hide()
});
});
Now I want the same thing, but with using a good old javascript function instead of the jQuery solution given above. How to do this? See my (not working) attempt here.
Many thanks
Here is a simple vanilla JS version:
function hide() {
var spans = document.getElementsByTagName('span'), i = 0;
for(i=0; i<spans.length; i++) {
spans[i].style.display = (spans[i].innerText.match(/^[1-9]+$/) ? 'none' : '');
}
}
Note: I've corrected your regex to match numbers with more than 1 digit in it.
Updated fiddle: http://jsfiddle.net/WnLUu/6/
In plain javascript you could access the style attribute, so instead of $(this).hide() you could call
this.style.visibility = "hidden"
Maybe something like this.
function buttonClicked(evt) {
var spans = document.getElementsByTagName("span");
for (var i = 0, length = spans.length; i < length; ++i) {
if (/^([1-9])$/.test(spans[i].innerHTML)) {
spans[i].style.display = "none";
}
}
};
document.getElementById("hide").addEventListener("click", buttonClicked, false);
Please try this (works on IE and other browsers, .innerText is IE specific):
function hide() {
var spans = document.getElementsByTagName('SPAN');
for (var i=0; i < spans.length; i++) {
alert(spans[i].textContent);
if (spans[i].textContent !== undefined && spans[i].textContent.match(/^[1-9]$/))
spans[i].style.display = 'none';
else if (spans[i].innerText !== undefined && spans[i].innerText.match(/^[1-9]$/)) // IE
spans[i].style.display = 'none';
}
}

wrapping text words in new line

I'm using the below code for wrapping long text, entered by users in a text area for commenting:
function addNewlines(comments) {
var result = '';
while ($.trim(comments).length > 0) {
result += comments.substring(0,70) + '\n';
comments = comments.substring(70);
}
return result;
}
The problem is shown in the below screen shot. Any ideas on how to solve it? Can we use lastindexof(" ") method to get the last space in a substring to solve this issue logically? Can anyone tweak this little code to make it right?
I believe wrapping a text by CSS is a better solution however there is a link here which may be helpful wrap-text-in-javascript
by the way i remember there is a JQuery plugin for wrapping text google it too.
Try word-wrap: break-word in CSS.
The word-wrap property is well supported by browsers (even IE 5.5+).
More info here: https://developer.mozilla.org/en-US/docs/CSS/word-wrap
Sample usage: FIDDLE
Try one of these:
word-wrap:no-wrap;
word-wrap: break-word
It might solve your problem
The ones above only work 99% of the time. This is the only one that works for me 100%:
http://locutus.io/php/strings/wordwrap/
Hi just apply some css on text area like
style="word-wrap: break-word;"
I use this css code for displaying in Torch browser and it works
I've tried word-wrap:break-word;overflow:ellipsis;....etc, but didn't work.
#xxx{
width: 750px;
word-break: break-word;
}
After looking for the perfect solution using regex and other implementations. I decided to right my own. It is not perfect however worked nice for my case, maybe it does not work properly when you have all your text in Upper case.
function breakTextNicely(text, limit, breakpoints) {
var parts = text.split(' ');
var lines = [];
text = parts[0];
parts.shift();
while (parts.length > 0) {
var newText = `${text} ${parts[0]}`;
if (newText.length > limit) {
lines.push(`${text}\n`);
breakpoints--;
if (breakpoints === 0) {
lines.push(parts.join(' '));
break;
} else {
text = parts[0];
}
} else {
text = newText;
}
parts.shift();
}
if (lines.length === 0) {
return text;
} else {
return lines.join('');
}
}
var mytext = 'this is my long text that you can break into multiple line sizes';
console.log( breakTextNicely(mytext, 20, 3) );
I had the same issue, I solved it using the below function.
function wordWrap(message, lineSize, breakPoint){
let wordsArr = message.split(" "),
wordsLen = wordsArr.length,
finalMsg = "",
linesArr = [""],
currLine = 0;
for(let i=0; i< wordsLen; i++){
if(linesArr[currLine].length + wordsArr[i].length > lineSize){
currLine +=1;
linesArr[currLine] = wordsArr[i] + " ";
} else {
linesArr[currLine] += wordsArr[i] + " ";
}
}
let linesLen = linesArr.length;
for(let i=0; i<linesLen; i++){
finalMsg += linesArr[i] + breakPoint;
}
return finalMsg.trim();
}
Hope this helps.

easy way to escape html using jquery in ie 8

I want to convert text such as "x < y" into the properly-escaped "x < y". I've been using the browser's built in escaping functionality to do this:
div = $('<div></div>');
div.text(my_text);
escaped_text = div.html();
This works great.... until I tested in IE 8, which eats line breaks when you call .html(). Is there a similarly concise, robust way of doing this that will work in IE 8 as well?
Underscore has escape/unescape methods. It is a very useful library.
You could exchange the html() method for the innerHTML property like so:
div = $('<div></div>');
div.text(my_text);
escaped_text = div[0].innerHTML;
You can give a try to this:
jQuery Code:
(function ($) {
$.fn.escapeHtml = function () {
var e = document.createElement("DIV"),
s = '';
e.innerHTML = $(this).val();
s = e.textContent || e.innerText || "";
e.remove();
return s.replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi, '');
}
})(jQuery);
How to Use:
// if you want to real input value then, go with jQuery '.val()' option
var htmlString = $('#yourelement').val();
// remove html character, go with jQuery '.escapeHtml()' option
var safeHtmlString = $('#yourelement').escapeHtml();
or you can use as jQuery plugin:
jQuery.escapeHtml()

Accessing elements by type in JavaScript

A while ago I was making some test in JavaScript,
and played with a code to get the text of all elements with a certain class.
Now I was trying to make something like this but obtain all elements by a certain type, for example all elements type="text"
Is there any way to do this in JavaScript or should I use jQuery?
var xx = document.getElementsByClassName("class");
for (i=0;i<xx.length;i++){
var str=xx[i].innerHTML;
alert(str);
}
If you are lucky and need to care only for recent browsers, you can use:
document.querySelectorAll('input[type=text]')
"recent" means not IE6 and IE7
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
The sizzle selector engine (what powers JQuery) is perfectly geared up for this:
var elements = $('input[type=text]');
Or
var elements = $('input:text');
var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
for (;i<l;i++) {
if (elems[i].type.toLowerCase() === "text") {
ret.push(elems[i]);
}
}
return ret;
}());

Categories