How to replace text in multiple divs according conditional? - javascript

I need to replace the text of many divs, where according to the text of each div, put a text or another.
Example: If the text is 0, replace it with "no quota" and if it is different from 0, put "Yes it has".
Html code:
<div><p id="text">1</p></div>
<div><p id="text">0</p></div>
<div><p id="text">1</p></div>
JS code:
$('#text').text(function(){
if($(this).text() == '0')
{
$(this).text('No quota');
}
else
{
$(this).text('"Yes it has');
}
});
But only changes the first element and the others left with the same text.
As I can change the text for each item? Greetings from Chile.

you have multiple instances of the same id. each id needs to be unique - which is why its only affecting the first item. Change the id to a class and you will be able to change each p to the new text. Also spotted a typo in the last else text (correctedin the code below).
<div><p class="text">1</p></div>
<div><p class="text">0</p></div>
<div><p class="text">1</p></div>
$('.text').each(function(){
if($(this).text() == '0')
{
$(this).text('No quota');
}
else
{
$(this).text('Yes it has');
}
});

ID is to be used as unique identification number hence only first item changed. Change ID to CLASS should solve the issue.

There are two problems.
First, as others have noted, you should be using a class instead of ID if you want to match multiple elements.
Second, when you give a function argument to .text(), it receives the old text as an argument, and should return the new text rather than calling .html() within it. So it should be:
$('.text').text(function(i, oldtext) {
return oldtext == '0' ? 'No quota' : 'Yes it has';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><p class="text">1</p></div>
<div><p class="text">0</p></div>
<div><p class="text">1</p></div>

Related

Iterate over every element and get only the content that is directly in the node

let's assume I have this code
<p>FirstLevelP
<span>SecondLevelSpan</span>
</p>
<p>FirstLevelP
<span>SecondLevelSpan
<p>ThirdLevelP</p>
</span>
</p>
Is it possible to iterate through every element that I have right now, but only get the content, that's in the direct node of it, modify the text and then have it in the original content?
Example, If I go through every $('p').each and would extract the text I would also get the text inside the span.
Basically this:
FirstelElement: FirstLevelPSecondLevelSpan
SecondElement: SecondLevelSpanSecondLevelSpanThirdLevelP
But I want to have it like this
FirstelElement: FirstLevelP
SecondElement: SecondLevelSpan
ThirdElement: FirstLevelP
FourthElement: SecondLevelSpan
FifthElement: ThirdLevelP
Is this possible?
In my research I already found this answer here
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
But this would only solve half of my problems. I would still need to modify the text in the original content! Thanks in advance guys.
EDIT FOR CLARIFICATION
So basically, want I want to achieve is something like this:
For every element, I want to check if there is a dot at the end. If not I want to add one. I already managed to do this for headlines, like this:
foreach (pq($content)->filter(':header') as $headline) {
if (substr(pq($headline)->text(), 0, -1) != '.') {
$content = preg_replace('#(' . pq($headline) . ')#', pq($headline) . '.', pq($content));
}
}
The problem, as I stated, is, that when I have nested elements it would add the dot after the whole element, and not after each sub element if neccessary.
To work with my "assumed" code, it should look like this
<p>FirstLevelP.
<span>SecondLevelSpan.</span>
</p>
<p>FirstLevelP.
<span>SecondLevelSpan.
<p>ThirdLevelP.</p>
</span>
</p>
But unfortunatley, it currently looks like this
<p>FirstLevelP
<span>SecondLevelSpan</span>.
</p>
<p>FirstLevelP
<span>SecondLevelSpan
<p>ThirdLevelP</p>
</span>.
</p>
Note the dots.
finding and changing text without child elements works this ways:
// search every element
$("body *").each(function(index, el) {
// find first text node
var node = $(el).contents().filter(function() {
return this.nodeType === 3;
})[0];
// change text
node.textContent = "new text";
});
Edit, Updated
Try
$("body *").each(function (i, el) {
if ($(el).is("p, span")) {
$(el).text(function (idx, text) {
var t = text.split("\n")[0];
// if `text` string's last character is not `.`
// concat `.` to `text` string ,
// return `text` original string's with `.` added
return t.slice(-1) !== "." ? t + "." : t
})
}
})
$("body *").each(function (i, el) {
if ($(el).is("p, span")) {
$(el).text(function (idx, text) {
var t = text.split("\n")[0];
return t.slice(-1) !== "." ? t + "." : t
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>FirstLevelP
<span>SecondLevelSpan</span>
</p>
<p>FirstLevelP
<span>SecondLevelSpan
<p>ThirdLevelP</p>
</span>
</p>

jQuery, selecting just number from id like "article-23"

All right, I have a div tag which got a class="blog-post" and id like id="article-23" (where "23" could be any number, as it is id of blog post in a database). I need to somehow get just a number from that id and than apply some rules to that div tag. So say:
if number from id % 2 == 0 {
set text colour black to associated div tag with class of blog-post
} else {
set text colour white to associated div tag with class of blog-post
}
Thats just a "pseudo" code to show logic that I wan't to apply dependent if number from id is even or odd, but the question remains same, how do I just get number from id like "article-23" ?
As simple as
var number = "article-23".match(/\d+/)[0];
But you have to be sure that any digit exists in the string, otherwise you'd get a error.
You can actually apply rules via function, which makes this the cleanest solution (in my opinion):
$(".blog-post").css('color', function () {
return +this.id.replace('article-', '') % 2 ? 'blue' : 'red';
});
http://jsfiddle.net/ExplosionPIlls/Jrc5u/
Try this:
$('.blog-post[id^="article-"]').each(function () {
if (parseInt(this.id.replace('article-', '')) % 2 === 0) {
$('#' + this.id).css('color', 'black');
} else {
$('#' + this.id).css('color', 'white');
}
});
jsFiddle Demo
As an alternative, HTML5 supports these things called "data attributes", which are specifically meant for attaching data to your DOM without abusing things like the "class" or "id" attributes. jQuery provides a handy .data method for reading these attributes in a more obvious way.
You can add your own numeric ID attribute using something like "data-id":
<div class="blog-post" data-id="23" />
$("#blog-post").each(function () {
console.log($(this).data("id")); // Look up the data-id attribute
});
If I'm understanding correctly, you want the number after the hyphen of the id tag of your .blog-post class.
var article = $(".blog-post").attr('id'); //get the id
var article = article.split("-"); // split it on hyphens
return article = article[article.length-1]; // return the last element

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.

How to use jquery to select all elements that have two specific attributes

I have some markup where a lot of id's have an id attribute, as well as innerText. I want to select each of these elements, performing a function on the id.
How do I do that?
Something like this?
$('[id]:not(:empty)').each(function(i, el) {
// do stuff
});
Give them a common class:
HTML
<div id="first" class="all"></div>
<div id="second" class="all"></div>
<div id="third" class="all"></div>
jQuery
$('div.all').each(function(index){
processid(this.id);
});
If you are talking about selecting elements whose id (or some permutation of it) is included in its text then
$('[id]').filter(function(){
return $(this).text().indexOf( this.id ) >= 0; // the this.id should be altered to match the permutation you seek ..
}).css('color','red'); // turn those to red
After you comment to #lonesomeday (at the question comments) here is what to do ..
$('[id]').each(function(){
processid(this.id);
});
First select by a regular ID selector and then loop over that selection by filtering .text() non-empty.
$("[id]").each(function() {
if ($(this).text() != "") {
// do stuff
}
});

Categories

Resources