How to get innerHTML value using only class? - javascript

I have a code similar to following:
<span class="subg">100</span>
<span class="subg">10000</span>
<span class="subg">1000000</span>
I want to access the inner value of any span using jQuery selectors. So for example if I want to get value of span having value 10000, I do following:
$('.subg:contains("10000")').text()
This works fine, but if I want to get value 100, then this approach is not correct as I want to get the first span value but since all 3 spans contain 100, all three will be matched.
Another approach I tried is this:
$('.subg[innerHTML="100"]')
But this doesn't seem to work, as innerHTML is not an attribute of span.
I don't know the order of spans.
Restrictions:
I cannot use loop.
I cannot give id.
I cannot change span to some other type.

I don't think you can do this via class. You'll need to filter out the elements that match instead.
function getText(n) {
return $('.subg').filter(function (i, v) {
return $(v).text() === n;
});
}
getText('100').css('color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="subg">100</span>
<span class="subg">10000</span>
<span class="subg">1000000</span>

Use filter to get targeted span value:
var result = $(".subg").filter(function() { return ($(this).text() === '1000000') }); // Change value to get desire result
console.log(result.text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="subg">100</span>
<span class="subg">10000</span>
<span class="subg">1000000</span>

UPDATED : I used filter to match what you want
$(".subg").filter(function() {
return $(this).text() === "100";
}).css("color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="subg">10000</span>
<span class="subg">1000000</span>
<span class="subg">100</span>

Related

jQuery get element attribute from nested element

I'm in a situation as follows:
<span class="inputgrp">
<span class="additem">
</span>
</span>
<input type="text" avl="abc">
I'm trying to get the value of the attribute avl from the input with a click event on class="inputgrp"
I have tried with:
$(".additem").click(function () {
var v = $(this).parent().find("input:text").attr("avl")
})
and
$(".inputgrp").click(function () {
var v = $(this).prev("span").next("input:text").attr("avl")
})
But without success. Would appreciate some guide as I have no clue what I am dong wrong.
$(".inputgrp").click(function() {
alert($(this).next("input:text").attr("data-avl"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="inputgrp">
<span class="additem">
1
</span>
</span>
<input type="text" data-avl="abc">
Use data attribute since avl is not a valid attribute
use .next() since input is next to the click element
.find searches for children of the current element. The input is not a child but a sibling of .inputgrp
$('.inputgrp').on('click',function() {
var v = $(this).siblings('input[data-avl]').attr('data-avl');
});
Use data-avl as an attribute to make it valid.
Use the .sibling() function to select any of the siblings
If the input element is always going to be the next element, use the .next() function
use a data-avl="" attribute on your html input element and in jQuery use .data('avl') to get the value of the attribute
$(".inputgrp").click(function() {
alert($(this).next("input:text").data("avl"));
})

How to replace text in multiple divs according conditional?

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>

multiple span calls of javascript value

In my header I have
function addusr() {
document.getElementById("usrout").innerHTML = document.getElementById("usrin").value;}
and in my text I have
code-bla bla bla<span id="usrout"></span> bla!! It works!
but if I try to call <span id="usrout"></span> again on the same page at a different location, none of the others appear.
Example:
text <span id="usrout"></span> more text, code... another <span id="usrout"></span>...
...
..
...
another <span id="usrout"></span> ...
Only the first one appears, why is this? How can I fix it?
An ID needs to be unique. You might want to consider classes instead.
When you’ve assigned classes to the HTML elements, your JavaScript code may look like this:
function addusr () {
var usrin = document.getElementById("usrin").value,
usrout = document.getElementsByClassName("usrout");
Array.prototype.forEach.call(usrout, function (el) {
el.innerHTML = usrin;
});
}
Explanation:
Instead of getElementById, we’re using getElementsByClassName which returns an array of elements having that particular classname. Thus a loop is required to set the innerHTML property of each retrieved element.
First of all, using same ID in more than one element is WRONG and against RFC.
You should make it a CLASS, not ID, and then...
document.querySelector(".usrout").innerHTML = ...
Every single element needs a unique ID.
For example
<span id="usrout1"></span>
<span id="usrout2"></span>
Alternatively, you could use classes as mentioned already
<span class="green"></span>
<span class="green"></span>
Then use a CSS selector such as document.getElementByClass
Element IDs must be unique, so getElementById will only ever return (at most) one element.
You need to use a different search, perhaps querySelectorAll, to get all the applicable elements. You can then loop through them, and set the necessary comment.
For example:
function addusr() {
var inputValue = document.getElementById("usrin").value;
var outputs = document.querySelectorAll("span.usrout");
for (var i = 0; i < outputs.length; ++i) {
outputs[i].textContent = inputValue;
}
}
<input id="usrin" type="text" />
<button type="button" onclick="addusr();">Update</button>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>

Need to get is any child inside an element is having a background

I need to find out is their any span having a style of background so I can get value from its attribute I have $(this). Structure is:
<div id="operative_time_limit" class="timedivd">
<span title="1 hours" data-y="1" data-x="0"></span>
<span title="2 hours" data-y="2" data-x="0"></span>
<span title="3 hours" data-y="3" data-x="0"></span>
<span title="4 hours" data-y="4" data-x="0"></span>
</div>
Using alert(jQuery(this).children().css('background').length); but always getting 0 as result
try this,
alert($('#operative_time_limit').find('span').length);
For span which has background-color property then try it like,
var c=0;
$('#operative_time_limit').find('span').each(function(){
if($(this).css('backgroundColor')) // or 'background-color'
c++;
});
alert(c);
I am not sure what exactly $(this) is in your context.
However the following:
var count = 0;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
count++;
}
});
alert(count);
Will do it. Further extrapolating from your question to presume that you want to extract some attribute (lets call it someAttr), from the span with a background of css, and there is only one such span. Assuming those are correct assumptions, the following will give you what you want:
var attributeValue;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
attributeValue = $(this).attr('someAttr');
}
});
You now have your desired value in attributeValue
The following line will give you the length of Children of $(this)
alert(jQuery(this).children().css('background').length);
You could use the following code to find all the span's that have background color other than white (assuming white is default color)
var length = $('#operative_time_limit').children().filter(function () {
return $(this).css('background-color') != 'rgba(0, 0, 0, 0)' && $(this).css('background-color') != 'transparent';
}).length;
here, variable length can be used to determine how many spans have background property
See working fiddle
use following
alert(jQuery(this).children().hasClass('background')).
hasClss determines whether any of the matched elements are assigned the given class.
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are

Remove DOM element if it contains a string

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

Categories

Resources