Remove DOM element if it contains a string - javascript

So I have this code where it checks if the Name exists and if it does it deletes the span tag it's nested in.
<div id="box">
<br>
<span style="font-size: 12px">
<a>
<span style="color: #000000">
<b>Name</b>
</span>
</a>
</span>
However name can be also placed in these tags:
<br>
<span>
<a>Name</a>
</span>
</div>
How would I use jquery to check it?
I've tried:
$('span:contains("Name")').remove();
$('span > a > span b:contains("Name")').remove();
Nothing seems to work.
Edit#2: Also there are br tags I just included them. I'd like to remove them only if they're before the removed tags.
Thanks.

You can use filter() if you want to target exactly element with text "Name", not as :contains which will target element with text e.g "Name with some other text...":
Set code inside .load() callback function
$('#box').load('myUri', function () {
$('#box span').has('b, a').filter(function () {
return $.trim($(this).text()) === "Name";
}).remove();
});
Equivalent to :contains would be:
$('#box span').has('b, a').filter(function(){
return $(this).text().indexOf("Name") != -1;
}).remove();
UPDATED FOLLOWING COMMENT:
$('#box').load('myUri', function () {
$('#box span').has('b, a').filter(function () {
var toRemoveSpan = $(this).text().indexOf("Name") != -1 ? true : false;
if (toRemoveSpan && $('span').prev('br').length) {
$(this).prev('br').remove()
}
return toRemoveSpan;
}).remove();
});
This will give the same than just: $('#box').empty();
If this is not behaviour you want, you have to be more specific in your question.

How about something like this:
$('a:contains("Name"),b:contains("Name")').parents("span").remove();

Based on the edit, you need to execute teh script after the element is loaded.
You need to make use of the callback of the loading method to do it, if you are using .load() then it has a success callback where you can make call this

Try this:
$(function () {
$('div#box span a span b:not(:contains("Name"))').remove();
})
DEMO

Related

Remove html element with javascript

When I press the Submit button if any error is generated then code create a span element.
My question is how I can clear the old error from the error container element, or if not possible then please sum up the errors.
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
I tried remove() but I cannot do it.
Thanks
you can remove the span with next().
next() finds the next sibling to the input field you are referring to.
it will give you the span:
el.next().remove();
you can use a class on the span f.e. class="validation-span"
el.next(".validation-span").remove();
this will make sure you only remove the span and no other element if existent :)
Add an span element after the input and set its HTML each time instead of using .after.
<input name="yourName">
<span class="errors"></span>
<script>
$(document).find('[name="'+i+'"] + .errors')
.html('<span style="color: red;">'+error[0]+'</span>');
</script>
I updated the both way you want, please pick which is more suitable to you
function logErrorCleanSpan(errorMessage){
$('#errorContainer').text(errorMessage);
}
logErrorCleanSpan("Hello");
logErrorCleanSpan("Jarvis");
function logErrorAppendSpan(errorMessage){
var span = $("<span>"+errorMessage+"</span>");
$('#errorContainerSpanAppend').append(span);
}
logErrorAppendSpan("1. Hello ");
logErrorAppendSpan("2. Jarvis ");
#errorContainerSpanAppend{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Append Error and clean the previous error<h3>
<span id="errorContainer"></span>
<h3>Append Error and keep the older one<h3>
<span id="errorContainerSpanAppend"></span>
Assign a id with index to span after each click remove previous span using id
Use jquery remove
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span id="error'+i+'" style="color: red;">'+error[0]+'</span>'));
if($(document).find('span#error+i - 1+')) {
$( "span#error+i - 1+" ).remove();
}
});
this is just an example code not correct code.

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);
});
});

Find exact string in element jQuery

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>

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.

Categories

Resources