Below is a sample structure from which i'm trying to get the specific value of custom attribute
<div id="123"></div>
<div id="456"></div>
<div context="james"></div>
Below is how i'm trying to fetch, but it always returns false.
if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}
The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:
var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")
You could also use .filter:
if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");
Note: If you used data-context="james" you would use the .data() method rather than .attr().
Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:
// Select by attribute
var theDiv = $("div[context='james']");
// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}
// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");
// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>
Related
I am working on javascript conditions.
If the field is empty I open an alert, else the function gets executed.
But I am trying to add another condition -- to verify the class of the field. If it is not in the page, or if it's empty, then directly execute the function/show an error.
How can I check with javascript if the class is in the page and if it's filled ?
$("#bouton").on("click", function(){
var warnning_message = 'warning message';
if(!$('.the-class').val()) {
alert(warnning_message);
}
else{
console.log('ok');
}
Seems hasclass will be useful
if($('.the-class').val()==='' && $('.the-class').hasClass('className')) {
alert(warnning_message);
}
You can check the existence of the class with $(".the-class").length > 0 code:
$("#botton").on( "click", function() {
var warnning_message = 'warning message';
if( $(".the-class").length > 0) {
alert(warnning_message);
}
else {
console.log('ok');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="botton" class="the-class">Click Here</div>
If you want to check whether an element with specific class exists or not use the following:
if ($(".the-class").length>0){
alert('Exists');
}
You could put ID to the field in order to select it and then do something like this:
if($( "#mydiv" ).hasClass( "the-class ))
console.log('has class');
else
console.log('no class');
Check the length of the array
if( $('.the-class').length == 0) {
alert(warnning_message);
}
else if (!$('.the-class').val()){
alert(warnning_message);
}
I am trying to make myself a personal user script, but I need to detect an html attribute's value. For example:
<div id="a">Stuff</div>
<div id="b" value="false"></div>
How could I create an if statement in the script, that triggers if the "value" attribute of element b turns to true?
element = document.getElementById("b");
if(element != null) {
if (element.value == "true") {
// do something
}
}
Check out this link... it says that you can import JQuery into your userscript.
youtube video
You can then get the value of any attrubute using jquery API for attr
Jquery Api attr
which can be done like
var bAttrValue = $("#b").attr("value");
You then coulld write a function which takes in an Id and an attribute like
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
var elemAttrValue = $("#"+elemId).attr(attribute);
return elemAttrValue;
}
You could then consume it like
var DivbValue = GetAttributeValue("b", "value")
if(DivbValue) //true
{
//do something
}
else //false
{
//do something
}
alternatively write this in JavaScript
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
element = document.getElementById(elemId);
return element[attribute];
}
<p></p> // return true
<p>something</p> //return false
I thought of using jquery's contains() but I think there's a better way of doing it in pure js?
You can use either childNodes or children in plain JS. Both return an array-like collection containing the children of an element. Both collections have a length property.
Note that both properties are live collections. You might want to shallow-copy them into an array. Here's an example of getting all children of body.
var hasContent = Array.prototype.slice.call(document.body.children).length;
I would use the old innerHTML to avoid JQuery like you want:
function hasSomething(id) {
var element = document.getElementById(id);
if (element && (element.innerHTML || '').trim())
return true;
else
return false;
}
return element.innerHTML.trim().length == 0;
Assume you've got a tag with id mydiv
<p id='mydiv'>Something</p>
if($('#mydiv').is(':empty'))
or
if($('#mydiv:empty').length)
can check whether it's empty.
SOmething like:
var myTextField = document.getElementById('myText');
if(myTextField.value != "")
alert("nothing")
else
alert("Would you please enter some text?")
}
Check function in the code below will do the job, You just need to call it. I have attached code in both jquery and javscript.
HTML :
<p id="data">Some text</p>
Jquery :
<script>
function check()
{
var len= $("#data").text().length;
if(len==0)
return true;
else
return false;
}
$(document).ready(function(){
document.write(check()); // call check function
});
</script>
Javascript:
<script>
function check() {
var x = document.getElementById("data").innerHTML;
if(x.length==0)
return true;
else
return false;
}
</script>
I have a class js-bootstrap3 that is generated by a cms. What I need to do is check if the containing element just has js-bootstrap3and .unwrap() the contents, but if the element has multiple classes which include js-bootstrap3 then I'm trying to just remove that class.
jsFiddle
$('.jsn-bootstrap3').each(function(){
if( $(this).attr('class') !== undefined && $(this).attr('class').match(/jsn-bootstrap3/) ) {
console.log("match");
$(this).contents().unwrap();
$(this).removeClass('jsn-bootstrap3');
}
});
This just seems to detect any element with js-bootstrap3as a class and unwraps it.
this.className is a string with all of the classes for the element (space delimited), so if it's not just "jsn-bootstrap3" you know it has more than one class:
$('.jsn-bootstrap3').each(function(){
if( $.trim(this.className) !== "jsn-bootstrap3") {
// Just jsn-bootstrap3
$(this).contents().unwrap();
} else {
// More than just jsn-bootstarp3
$(this).removeClass('jsn-bootstrap3');
}
});
Dependeing on the browsers you need to support element.classlist (IE10+) might or might not be what you need.
classList returns a token list of the class attribute of the element.
classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className. It contains the following methods:
Otherwise you're looking at splitting the className into an array like so to count the values:
var classes = element.className.split(" ");
Building on your example you could do something liket his:
$('.jsn-bootstrap3').each(function(i, el){
if( el.className.indexOf('jsn-bootstrap3') != -1 ) {
console.log("match");
if ( el.className.split(" ").length > 1 ) {
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
}
});
Try this code.
$(document).ready(function(){
$('.jsn-bootstrap3').each(function(){
var classes = $(this).attr('class');
var new_cls = classes.split(' ');
if( new_cls.length > 1 ){
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
});
});
How can I check if a given DOM element is a a checkbox.
Scenario:
I have a set of textboxes and checkboxes in which the values are assigned dynamically. I don't have a way to identify if the DOM element is a checkbox or a textbox.
Using only vanilla javascript you could do
if (el.type && el.type === 'checkbox') {
...
}
or even shorter
if ((el || {}).type === 'checkbox') {
...
}
or in modern browsers you could use matches()
if (el.matches('[type="checkbox"]') {
...
}
If you're using jQuery, you can use the :checkbox pseudo-class selector along with is method:
if($("#that-particular-input").is(":checkbox")) {
}
Checks anything
function isCheckbox (element) {
return element instanceof HTMLInputElement
&& element.getAttribute('type') == 'checkbox'
}
if( $(element)[0].type == "checkbox" ) {
}
OR
if( $(element).is(':checkbox') ) {
}
Take a look at the checkbox selector.
var checkboxes = $("form input:checkbox");
You can tell what type an input is like this:
if ($(".your-input").is(":text"))
{
// Textbox
}
else if ($(".your-input").is(":checkbox"))
{
// Checkbox
}
if (<DOMNode>.type === "checkbox") {
// ...
}
Try this;
$(element).is(':checkbox');
here element is selector to your element
if( $(element).is(':checkbox') ) {
// do something
}
jQuery is():
if ($el.is(':checkbox')) { ... }
You can use the pseudo-selector :checkbox with a call to jQuery's is function:
$('#myinput').is(':checkbox')
You should have a decent naming convention which allows you to know if an element is a checkbox from just seeing it's id or name.
e.g. "chkMyCheckbox"