jQuery - Selectors for an element with a specific attribute - javascript

on my page I have many label tags. Some of them has the for attribute. How should be the jQuery's selector of that label's ?

Try this,
Live Demo
$("label[for]")​

Try this: $('label[for]') if you don't know what is equal to for

A selector like this one will be helpful :
$('label[for="foo"]').css('color', 'red);
EDIT after comment :
To select all labels without knowing the for value :
$('label[for]').css('color', 'red);

Related

Check is style attribute does not exists using javascript selector method

I'm trying to only select ARTICLE items that do not have the style attribute set.
I could do this easily with jQuery but I'm using a library that is javascript only, called scrollreveal.
I can easy get items that have the style attribute using this ARTICLE[style].
But I want to reverse this and get items that do not have a style attribute, in the same way using a not equal to != operator on the selector.
I've tried this...
// scroll reveal article
window.sr = new ScrollReveal({ reset: false });
sr.reveal('ARTICLE[!=style]', {
duration: 1000
});
But it's not working as expected, does anyone know if its possible to achieve this using not equal too on a attribute selector?
Thanks in advance for any help on this.
Almost there. The :not pseudoclass should do the trick:
article:not([style])
Just use :not([style]):
const matches = document.querySelectorAll('div:not([style])')
console.log(matches)
<div id="foo" style="width:100px;"></div>
<div id="bar"></div>
<div id="baz"></div>
That is if I'm correct in assuming that sr.reveal uses document.querySelector internally.

jQuery span class selector

I have a span with a text inside it like :
<span class="characters-count">(160 Characters Left)</span>
given the span a class in this case .characters-count , when i tried class selector using jQuery to get the text inside span :
$(".characters-count")[0].text();
it returns undefined !
However this selector works well :
$("span.characters-count").text();
anyone can explain what is happening ?
$("span.characters-count").text();
In our case you work with jQuery Object that has text method
$(".characters-count")[0].text();
In this case you work with actual DOM element (like document.getElementByClassName('characters-count')[0]) that does not have text method
Use
$(".characters-count").text();
Demo
console.log($(".characters-count:first").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="characters-count">(160 Characters Left)</span>
try something like this:
$(".characters-count:first").text()
Check here, why it was not working for you.
//This will return dom element, so it doesn't have `text()` method, that's why it was throwing error for you.
console.log($(".characters-count:first")[0]);
// This will return object of an element, you can use jQuery selectors to get first element from collection and set text to it
console.log($("span.characters-count"));
console.log($("span.characters-count:first").text
);
you need to use innerText instead of text() when you use $(".characters-count")[0] check DEMO
$(".characters-count")[0].innerText

Select a div insinde another div with jQuery

So I try to select a div within another div. My html goes like this:
<div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div>
I want to select my #cube0 within my Stage_game_page specifically, with jQuery or JS.
The goal of the selection is to use it in an loop.
I tried :
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#Stage_game_page")$("#cube"+i)[...]
}
I don't understand what I'm doing wrong.
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#cube"+i);
}
This is sufficient to select the "#cube0"/"#cube1"/"#cube2" etc. especially since ids are always unique. To answer the question $("#cube0", "#Stage_game_page")... that is how you select a div in another div
The id attribute should only be used once! I see above that you're using id="cube0" twice. If you want your divs to be recognized in multiple instances, use a class instead (the . instead of the #). Using the same id twice will probably break your script.
I believe for your html, you could use id "cube0", "cube1", etc., as long as you're ok with entering them manually. That should work for the loop you'd like to use.
Loops through each div that starts with the id cube inside Stage_game_page1
$("#Stage_game_page1 > div[id^='cube']").each(function () {
alert($(this).html());
});
JSFiddle
Child Selctor
Starts with Selector
use each() for loop.
$('#Stage_game_page1').children().each(function(index) {
// your code here with index starts from 0
});
or this using jquery attribute starts with selector
$('#Stage_game_page1').find('[id^="cube"]').each(function(index) {
// your code here
});
You need to use .find() or .children() or the like.
The correct jQuery usage would be
$("#Stage_game_page").find('#cube'+i)
to find a div with that id inside the container #stage_game_page
You have duplicate cube0 in your html code..
and i think the look should contain something like that:
$("#cube"+i)[...]
One another solution is:
$("#Stage_game_page1 div[id='cube0']")

jQuery selectors on custom data attribute that are not empty

I want to create a simple custom tooltip plugin for jQuery that for every element that has a data-custom-tooltipset. So, something like :
Hhahaha
OR
<button data-custom-tooltip="This is my tooltip for the button Tex">Haha Button :) </button >
So, the function to display the tooltip would be triggered only if the data-custom-tooltip is NOT empty.
Close enough to this : jQuery selectors on custom data attributes using HTML5
You can use :not() selector and remove the empty ones
$('[data-custom-tooltip]:not([data-custom-tooltip=""])')
or
$('[data-custom-tooltip]').not('[data-custom-tooltip=""]')
or based on what #VisioN said in the comments with the Not Equal Selector
var xxx = $('[data-custom-tooltip][data-custom-tooltip!=""]');
use like this
$("[data-custom-tooltip]:not([data-custom-tooltip='']").click(function(){alert("clicked");});
fiddle
Try
.filter()
var tooltip_el = $('[data-custom-tooltip]').filter(function () {
return $.trim($(this).data('custom-tooltip')) != '';
});

Add and remove item dynamically in dropdown

How can I add or remove dropdown items dynamically in jQuery? Below code is not working
$("#dropdownId").remove("<option value='12'>testing</option>");
$("#dropdownId").add("<option value='12'>testing</option>");
Can anyone suggest a way to do this?
To add elements, use .append():
$('#dropdownId').append('<option value="12">testing</option>')
or .appendTo():
$('<option/>', { val: 12, text: 'testing' }).appendTo('#dropdownId');
To remove, use .remove() differently:
$('#dropdownId').find('option').filter(function ()
{
return this.value === '12' && $(this).text() === 'testing';
}).remove();
As a general recommendation, you should really read the API docs for simple jQuery questions like these. If you had read the documentation for .add(), for instance, you'd see that it does not do what you thought.
Use a standard selector for the item you want to remove, rather than passing html markup:
$('#dropdownId option[value="12"]').remove();
// or
$('#dropdownId').remove('option[value="12"]');
(I'm assuming you don't have more than one option with the same value.)
The (approximate) opposite of .remove() is .append():
$("#dropdownId").append("<option value='12'>testing</option>");
Remove:
$("#selectList option[value='2']").remove();
Add:
$('#selectList').append('<option>'+val+'</option>');
Use append instead of add !
add is not writing method.
use append() like,
$("#dropdownId").append("<option value='12'>testing</option>");
here's some information from jQuery API: http://api.jquery.com/append/

Categories

Resources