Find exact string in element jQuery - javascript

I have a couple of span elements inside a container and I want to match the exact word of one of the spans to insert a banner. I cant figure out how to do this.
First i tried this script:
$(document).ready(function(){
if ($('.head.titlebox span').text().trim() === "match" ){
$('<span class="myAwesomeBanner4"></span>').insertAfter(".productbox em.price.product-card-price")
}
else if ($('.head.titlebox span').text().trim() === "matchother" ){
$('<span class="myAwesomeBanner5"></span>').insertAfter(".productbox em.price.product-card-price")
}
});
This doesnt work - unless I remove the string it should match: === "". So the script seems kike it kinda works. I cant match it to the words though - looks like its correct to me, so not sure why it's not working.
Then I tried this script which works - but I cant figure out how to convert it to use if statement and to create my div to insert in the DOM like above:
$('.head.titlebox span').filter(function(index) {
return $(this).text() === "match";}).css("background", "black");
My HTML for targeting the string:
<div class="head titlebox">
<span id="artid">text</span><h1 id="prod-title">text</h1>
<span>text</span><span>text</span>
<span>match</span>
</div>
So why is the first not working - and how do I combine it with the working filter function of the second script?

You need to loop through all the span tags,
$('.head.titlebox span').each(function() {
if ($(this).text() == "match") {
//insert your html.
}
})

try this:
$(".head").on("click", function() {
var spanList = $(".head span");
$.each(spanList,function(span){
console.log($(spanList[span]).text());
if($(spanList[span]).text() === "match"){
console.log("Matched")
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="head titlebox">
<span id="artid">text</span>
<h1 id="prod-title">text</h1>
<span>text</span><span>text</span>
<span>match</span>
</div>

Related

wrap text with div excluding all children

I have got a problem which I have been trying to solve for past 2 days, but couldn't solve it.
Problem:
I have a HTML as
<div class="string-box">
Text 1 wrap me
<span class="inner-span">Don't search me</span>
<span class="inner-span">Identical text</span>
Identical text
substring match
<span class="inner-span">Don't search substring match</span>
<br>
Finally wrap me
</div>
I want to wrap the content has below
<div class="string-box">
<span> Text 1 wrap me </span>
<span class="inner-span">Don't search me</span>
<span class="inner-span">Identical text</span>
<span>Identical text</span>
<span>substring match</span>
<span class="inner-span">Don't search substring match</span>
<br>
<span>Finally wrap me</span>
</div>
What I have tried
a) I firstly tried to search for string in the html and used string replace to replace the string with wrapped string.
The problem with this approach is that it replaces things in child too..
b) I tried cloning the node and removing all child , but then I am lost with the position of the string.
c) I tried the following code to replace textNode, but I ended up getting HTML
$('.string-box').contents().filter(function(){
return this.nodeType == 3;
}).each(function(){
this.nodeValue = '<span>'+this.nodeValue+'</span>';
})
Thanks in advance for you time & help..
Your code is close, however the nodeValue cannot contain HTML - hence why it gets encoded in your attempt. Instead you can wrap() the textNode in HTML, like this:
$('.string-box').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
$(this).wrap('<span />');
})
Working example
Update
Here's a fix for occasions where the nodeValue contains a line break, and you want to wrap each line of the node in its own span:
$('.string-box').contents().filter(function() {
return this.nodeType == 3 && this.nodeValue.trim();
}).each(function() {
var $spans = this.nodeValue.trim().split(/\r?\n/).map(function(i, v) {
return $('<span />', { text: i + ' ' });
});
$(this).replaceWith($spans);
})
Working example
Just do it only in an each and you're fine. No need for filter the elements first. And you can use jQuery to wrap the content in a span.
$('.string-box').contents().each(function() {
if( this.nodeType == 3 )
$(this).wrap('<span />');
});
Working example.
As you already have a jQuery answer, allow me to offer a plain JavaScript alternative:
var stringBoxes = document.querySelectorAll('.string-box'),
stringBoxArray = Array.from(stringBoxes),
newElement = document.createElement('span'),
clone,
children;
stringBoxArray.forEach(function(box){
children = Array.from( box.childNodes ).filter(function(child){
return child.nodeType === 3;
}).forEach(function (text) {
clone = newElement.cloneNode();
text.parentNode.insertBefore(clone, text);
clone.appendChild(text);
});
});

Test to see if characters present in div id

I need some help fixing this code in order to change this JQuery if/else statement to test if a number is present within the div id "demo". Currently the code writes "Empty" when the div has no text inside of it and writes "Full" when it does.
<div id="demo"> </div>
<script type="text/javascript" src="jquery.js"></script>
<script>
if( $('#demo').is(':empty') ) {
document.write("Empty");
} else {
document.write("Full");
}
</script>
What I want to happen is for the statement to write "Empty" when there is any space or white-space inside, and for it to write "Full" when there is a numerical value inside the div.
if ($('#field > div.field-item:contains("someText")').length > 0) {
$("#somediv").addClass("thisClass");
}
Edit: Omitted any humor.
I suggest using a regular expression to determine what text is in your div:
var text = $('#demo').text();
if( text.match(/\s+/)) {
document.write("Empty");
} else if (text.match(/\d+/)) {
document.write("Full");
}

search contents of a div with multiple classes for a string nested in elements with jQuery

I would like to be able to look in the first span within a div with a class of t_links and buy and detect if the string Account appears. If it does then I want to set some tracking code in jQuery/JavaScript.
There will always be one span within this div. How can I search the contents for an instance of Account using jQuery?
<div class="t_links buy">
<span><a class="" href="https://www.ayrshireminis.com/account/login/">Account</a></span>
</div>
:contains is what you're looking for:
$(".t_links.buy span:first:contains('Account')")
http://api.jquery.com/contains-selector/
Edit: Added first as #adeneo pointed out. This will ensure that it's the first span that you're looking at.
Try (See Demo)
​$(document).ready(function () {
if($('.t_links.buy span').text().indexOf('Account')) {
// code
}
});​
Or
​$(document).ready(function () {
if($(".t_links.buy span:contains('Account')").length) {
// code
}
});​
Span has exact match :
if ($("span:first", ".t_links.buy")​.filter(function() {
return $(this).text() === 'Account';
})​.length) {
//set tracking code
}
Span contains :
if ($("span:first", ".t_links.buy")​.filter(function() {
return $(this).text().toLowerCase().indexOf('account') != -1;
})​.length) {
//set tracking code
}
If there is only one span, you can drop the :first.

Populating a "p" tag in HTML with Jquery

I cant figure out the syntax for this iv browsed the net when i mention "P" it returns multiple searches regarding PHP
What i want to do is populate a p tag text with a variable value?
This is my Jquery
$('.FOS, .MF, .CW, .OO, .LL, .CO, .TAK, .FCS, .CO').mouseover(function(e) {
var tr = $(this).closest('tr');
var Comments = tr.find('.GeneralComments').text();
if (Comments != "") {
$('div#pop-up').show();
$('p').text == Comments;
} else {
$('div#pop-up').hide();
}
return false;
});
Im trying to assign the value from Comments to the p.text but its not working?
Heres my div where the p take is situated.
<div id="pop-up">
<h3>
Over all Notes</h3>
<p>
This is where i want the value from comments to appear?
</p>
</div>
Any help would be appreciated, thank you.
This will fill the paragraph tag inside #pop-up with the text inside the Comments variable
$("#pop-up > p").text(Comments);
I suggest you have a read of the API here.
Here is the right syntax.
$("#pop-up > p").text(Comments);
Best way is to add ID for that p tag. and use ID to populate comments, like add id comments to that p tag and you can use:
$("p#comments").text(Comments);
if (Comments != "") {
$('div#pop-up').show();
$('p').text(Comments);
}
== is a comparison operator, not an assignment operator.
Also in jQuery, you pass the assignment you want to make into the function as an argument.
if (Comments != "") {
$('div#pop-up')
.show()
.find('p')
.text(Comments);
}
See docs for the .text() method.

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

Categories

Resources