I dont have access to the following HTML its displayed dynamically using some External JS.
<td class="quantitybox">
<span class="qty">Quantity</span>
<br style="clear:both;">
:<input type="text" value="1" onkeydown="javascript:QtyEnabledAddToCart();" maxlength="8" size="3" name="QTY.1121309" class="v65-productdetail-cartqty">
</td>
I want that : after to be Removed/Deleted using Jquery, but i am not getting what handler should be used shall i apply a class to <br> dynamically and do something to it
The jQuery way, without regex:
$('td.quantitybox').contents().filter(function(){
return this.nodeType === 3 && // textNode
$.trim(this.nodeValue) === ":";
}).remove();
Or simply change the textnode to an empty string:
$('td.quantitybox').contents().filter(function(){
return this.nodeType === 3 && // textNode
$.trim(this.nodeValue) === ":";
})[0].nodeValue = "";
If you have multiple textnode with colons- : that you want to remove:
$('td.quantitybox').contents().filter(function() {
return this.nodeType === 3 && // textNode
$.trim(this.nodeValue) === ":";
}).each(function() {
this.nodeValue = "";
});
If you want to do it with regex and aware of it's risks:
$('td.quantitybox').html(function(i, old){
return old.replace(/:\s*</, '<');
});
Note that your HTML code in the question was edited, so I added the white space to the regex so it will work with the initial markup as well....
I'd suggest, though currently untested, the following:
$('td').each(function() {
var i = this.getElementsByTagName('input'),
text = i.previousSibling.nodeValue.replace(/:/g, '');
i.previousSibling.nodeValue = text;
});
$(document).ready(function(){
var texts = $('input').map(function(){
var text = this.previousSibling.nodeValue;
this.previousSibling.nodeValue = text.replace(/:/g, '');
});
});
Another solution. Example: http://jsfiddle.net/k25yx/1/
$(document).ready(function() {
// Cache Object
var obj = $('.quantitybox');
obj.each(function(){
var that = $(this);
// remove br
that.find('br').remove();
// trim colon
that.html(function(i, val) {
return val.replace(':', '');
});
})
});
Related
<h1>
<br>
USA
<br>
<br>
<p style="margin-top:13px;" class="glyphicon glyphicon-chevron-down"></p>
<br>
<br>
Canada
</h1>
Without changing the HTML above, how can I get the value of Canada with jQuery selector?
If you want to get the last text-node value, then try this
var h1 = document.querySelector("h1");
var childNodes = h1.childNodes;
console.log(childNodes[childNodes.length -1 ].nodeValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><br>USA<br><br><p style="margin-top:13px;" class="glyphicon glyphicon-chevron-down"></p><br><br>Canada </h1>
Equivalent jquery would be
var h1 = $("h1")[0];
If the markup style is consistent -- not prone to change, you can use xpath.
https://developer.mozilla.org/en-US/docs/Web/XPath
You can also do something like this:
var value = $('h1').contents().filter(function() {
return this.nodeType == 3;
})[1];
Here i use nodeType == 3, which selects text nodes.
https://jsfiddle.net/54tw4nw0/
Here you go:
var afterP;
var text = $('h1').contents().filter(function() {
if (this.nodeName == "P") {
afterP = true
}
return afterP && this.nodeType == 3;
}).text();
console.log(text);
Solution copied & enhanced from Get the text after span element using jquery
Try :
var text = $("h1").html();
alert(text.substring(text.lastIndexOf("<br>") +4));
Working Fiddle
I have this text inside a blockquote:
<blockquote class="tr_bq">
4 Text<br />
20 TExt<br />
2 Another text a little longer<br />
<br />
20 text</blockquote>
I want to add for each line a tag or convert the br to include a class. if the br was including all the line i would know how to do it. This is how i want to end like:
<blockquote class="tr_bq">
<strike>4 Text</strike><br/>
<strike>20 TExt</strike><br/>
<strike>2 Another text a little longer</strike><br/>
<br />
<strike>20 text</strike></blockquote>
or
<blockquote class="tr_bq">
<br class="X">4 Text<br>
<br class="X">20 TExt<br>
<br class="X">2 Another text a little longer<br>
<br />
<br class="X"> 20 text</br></blockquote>
I've tried with wrap but with no sucess, any way to do this?
You can do this by manipulating the inner HTML of the blockquote.
$('.tr_bq').each(function () {
var html = $(this).html();
var newHtml = html.split('<br>').map(function (str) {
return '<strike>' + str + '</strike>';
}).join('<br>');
$(this).html(newHtml);
});
Just to offer a plain-JavaScript means of achieving this, avoiding the (unnecessary) use of a library:
function wrapNodesWith(nodes, tag) {
// if we have neither nodes to wrap, nor a tag to wrap
// them with, we quit here:
if (!nodes || !tag) {
return false;
}
// otherwise:
// we convert the nodes to an array (using Array.prototype.slice,
// in conjunction with Function.prototype.call):
nodes = Array.prototype.slice.call(nodes, 0);
// if the tag parameter passed to the function is a string ('strike'),
// we create that element using document.createElement(tag),
// otherwise we assume we've got an HTMLElement (this is a very
// naive check) and so we use that:
tag = 'string' === typeof tag ? document.createElement(tag) : tag;
// an unitialised variable for use within the following forEach:
var clone;
nodes.forEach(function(n) {
// n is the node over which we're iterating,
// cloning the tag (to avoid multiple calls
// to document.createElement):
clone = tag.cloneNode();
// setting the textContent of the clone to the nodeValue
// of the node (if it's a textNode), or to the textContent of
// element (again a simple check):
clone.textContent = n.nodeType === 3 ? n.nodeValue : n.textContent;
// replacing the childNode, using parentNode.replaceChild(),
// inserting clone and removing n:
n.parentNode.replaceChild(clone, n);
});
}
// finding the first <blockquote> element:
var blockquote = document.querySelector('blockquote'),
// creating an array of the childNodes of the <blockquote>:
children = Array.prototype.slice.call(blockquote.childNodes, 0),
// filtering the children array, retaining only those nodes for
// which the assessment returns true:
textNodes = children.filter(function(n) {
return n.nodeType === 3;
});
// can be called with:
wrapNodesWith(textNodes, 'strike');
// or:
wrapNodesWith(textNodes, document.createElement('strike'));
function wrapNodesWith(nodes, tag) {
if (!nodes || !tag) {
return false;
}
nodes = Array.prototype.slice.call(nodes, 0);
tag = 'string' === typeof tag ? document.createElement(tag) : tag;
var parent, clone;
nodes.forEach(function(n) {
clone = tag.cloneNode();
clone.textContent = n.nodeType === 3 ? n.nodeValue : n.textContent;
n.parentNode.replaceChild(clone, n);
});
}
var blockquote = document.querySelector('blockquote'),
children = Array.prototype.slice.call(blockquote.childNodes, 0),
textNodes = children.filter(function(n) {
return n.nodeType === 3;
});
wrapNodesWith(textNodes, 'strike');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<blockquote class="tr_bq">
4 Text
<br />20 TExt
<br />2 Another text a little longer
<br />
<br />20 text
</blockquote>
References:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.slice().
Conditional ('ternary') operator.
document.createElement().
document.querySelector().
Function.prototype.call().
Node.nodeValue.
Node.replaceChild().
Well,
i managed to get it working with this:
var pre = document.getElementsByTagName('blockquote'),pl = pre.length;
for (var i = 0; i < pl; i++) {
var pro = pre[i].innerHTML.split(/<br>/), pz = pro.length;
pre[i].innerHTML = '';
for (var a=0; a < pz ; a++) {
pre[i].innerHTML += '<strike>' + pro[a] + '</strike><br/>';
}
}
I'm trying to a way to get the first number value present inside a table (and respective tbody), but it needs to be able to find the value the first number, and ignores all the tags it comes accross until it reaches the number value.
<table id="TableID">
<thead></thead>
<tbody>
<tr></tr>
<tr>
<td></td>
<td>
<div>
<div>
<span>
4031007
</span>
</div>
<div>
<span>
whatever
</span>
</div>
</div>
</td>
<td></td>
</tr>
</tbody>
</table>
in the above example, we would try to find 4031007, which is inside a <span>, but it could've been a <div> or something else. I need this without using JQuery. Any help?
You could do it the plain old way: make a recursive function that will return text of the first node which has a text content:
function findFirstNumber(node) {
// If this is a text node, return its contents. Trim it because there is
// whitespace between the elements that should be ignored
if (node.nodeType == Node.TEXT_NODE)
return node.textContent.trim();
// Iterate over all child nodes and finde the first one that has text in it
for (var child = node.firstChild; child; child = child.nextSibling) {
var content = firstText(child);
if (content && isNumber(content))
return content;
}
// No text found
return '';
}
function isNumber(value) {
return !!isNaN(value);
}
console.log(findFirstNumber(document.getElementById('TableID')));
I used the mdn page about Node to find out how to do this.
see fiddle (open your console)
How about a fancy find function that accepts regular expressions.
function findRegExp(start, reg, mod) {
if (! (reg && start)) return this;
return [].slice.call(start.querySelectorAll('*')).filter(function(elem) {
if (typeof reg == 'string')
reg = new RegExp(reg, mod ? mod : '');
var clone = elem.cloneNode(true),
child = clone.children;
for (var i=child.length; i--;)
clone.removeChild(child[i]);
var txt = clone.textContent.trim();
return reg.test(txt);
});
}
to be used like
var elems = findRegExp(document.getElementById('TableID'), /^\d+$/);
FIDDLE
and the jQuery version
$.fn.findRegExp = function(reg, mod) {
if (!reg) return this;
return this.find('*').addBack().filter(function() {
if (typeof reg == 'string')
reg = new RegExp(reg, mod ? mod : '');
var c = $(this).clone();
c.children().remove();
var txt = $.trim(c.text());
return reg.test(txt);
});
}
Then you can search for an element containing only numbers
$('#TableID').findRegExp(/^\d+$/);
FIDDLE
I have a definition list with associated variables and their values. (see fiddle too)
<dl id="myVars">
<dt class="var-name">%name%</dt>
<dd class="var-name">Joe Sample</dd>
<dt class="var-phone">%phone%</dt>
<dd class="var-phone">555-1212</dd>
</dl>
I also have a textarea that one can use any of the above variables within their text. For example:
<textarea>Hello %name%, is this still the right phone number: %phone%?</textarea>
Finally there's a preview div where one can see the interpreted text after the variables are replaced. Like so:
<div id="preview"></div>
Can you help me come up with an efficient way to use jQuery to show live previews at the same time it replaces variables with their values?
Here's a handy fiddle if you're up for helping: http://jsfiddle.net/XAzZr/
http://jsfiddle.net/NFtVc/
var subst = {}, // store substitutions in an object to eliminate DOM lookups
substRegex = /(.*)%(\S*)%(.*)$/i;
function defineSubst(){
$("#myVars dd").each(function(){
var cls = this.className.split(' '),
l = cls.length;
while (l--){
if (cls[l].indexOf('var-') == 0)
subst[cls[l].replace(/var-/, "")] = this.innerHTML;
}
});
}
function getSubst(key){
if (typeof subst[key] == "undefined")
return "[INVALID CODE]";
else
return subst[key];
}
function updatePreview(){
var txt = $('textarea').val().split(' '),
newTxts = [],
regex = /(.*)%(\S*)%(.*)$/i;
$.each(txt, function(){
var m = substRegex.exec(this);
if (m)
newTxts.push(m[1] + getSubst(m[2]) + m[3]);
else
newTxts.push(this);
});
$("#preview").text(newTxts.join(' '));
}
$('document').ready(defineSubst);
$('textarea').keyup(updatePreview);
$('textarea').on('keyup', function() {
var message = this.value.replace(/%(.*?)\S+/g, function(val) {
var elem = $('dt').filter(function() {
return $(this).text() == val;
});
return elem.length ? elem.next('dd').text() : '';
});
$('#preview').text(message);
});
FIDDLE
I need to import some formatted html text in a input textarea value
i use jquery
so what's the best way to do it?
i guess first off i need to replace the then strip out the rest (bold, italic, images etc..)
In my first response I didn't see that you wanted to retain line breaks, so here's a better version. It replaces br with an unlikely string %%br%% and then at the end replaces them with new line (\n). So if that string actually appears in the text, it will be replaced by a new line. You can change that to anything you like, just make it something that is unlikely to be encountered in the text.
<script>
function removeMarkup(m) {
var d = document.createElement('div');
d.innerHTML = m;
var c = 0;
// Make brString something that should never appear in the text
// and has no special meaning in a RegExp
var brString = '%%br%%'
var re = new RegExp('\\s*' + brString + '\\s*','g');
function getTextWithReturns(node) {
var tag = node.tagName && node.tagName.toLowerCase();
var nodes = node.childNodes;
var type = node.nodeType;
var s = '';
// Deal with br
if (tag == 'br') {
return brString;
}
if (nodes && nodes.length) {
for (var i=0, iLen=nodes.length; i<iLen; i++) {
s += getTextWithReturns(nodes[i]);
}
} else if (type == 3 || type == 4) {
s += node.nodeValue
}
return s;
}
return reduceWhitespace(getTextWithReturns(d)).replace(re,'\n');
}
function reduceWhitespace(s) {
return s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');
}
</script>
<div id="d0">some text <i>more</i> text
<p>Here is a paragraph with some <b>bold</b> and <i>italic</i> text, plus a <span>span</span> and a line break break break<br> about there.</p>
<p>Here is another paragraph with some <b>bold</b> and <i>italic</i> text, plus plus a <span>span</span> and a line break <br> here.</p>
</div>
<form>
<textarea id="ta0" rows="10" cols="50"></textarea>
<button type="button" onclick="
var ta = document.getElementById('ta0');
var div = document.getElementById('d0');
ta.value = removeMarkup(div.innerHTML);
">Set value</button><input type="reset">
</form>
$("#my_textarea").change(function(){
var cleanText = $("<span />").html(this.value);
this.value = cleanText.text();
});
Example: http://jsfiddle.net/6WbXN/