Get element with certain ID using .is() method - javascript

This should be very simple, but I just can't make it work.
I am trying to find an element with certain ID using .is() method:
http://jsfiddle.net/4hbvgwnv/
<div id="foo">Some text</div>
$(document).ready(function() {
var id = "foo";
alert( $("div").is("#" + id).text() );
}):
But this just won't work. What am I doing wrong?
PS: I know I can select an element with $("#foo"), but I want to use the .is() method.

You need to use filter() which filter elements based the selector. is() will return a Boolean value not the jQuery object, returns true at least one element is matched else returns false.
$(document).ready(function() {
var id = "foo";
alert($("div").filter("#" + id).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Some text</div>
Instead you can simply use selector $("div#" + id) which select div with that particular id. It will only select element is div.
$(document).ready(function() {
var id = "foo";
alert($("div#" + id).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Some text</div>

http://api.jquery.com/is/
.is() returns a boolean, if you check your developer console you got an error showing that "text" isn't valid !
Are you sure that .is() can be used for that intent ?
A solution that might work (kinda weird way to do it tho) : http://jsfiddle.net/4hbvgwnv/1/
$( document ).ready(function() {
var id = "foo";
if($("div").is("#" + id))
alert($("div").text());
});

is() returns a boolean, you should use filter() instead:
$("div").filter("#" + id).text()
That said, if you're searching by id, you don't need to bother with a parent selector at all:
$('#' + foo).text()

Related

How can I check whether element exists based on the classname?

As I mentioned in the title of my question, my element doesn't have id attribute. So how can I check whether it exists or not?
Here is my HTML:
<div class="classname">something</div>
Note1: I can do that if there is a id attribute like this:
var el = document.getElementById("idname");
if ( el ){
console.log("exists");
} else {
console.log("not");
}
But I want to know how can I do that based on the class name .. is it possible?
Note2: I use jQuery.
Vanilla javascript (without jQuery or any other lib):
var els = document.getElementsByClassName('className')
var first = els[0]
Notice that this is an array, since there could be many elements with that class
With jQuery:
var els = $('.className')
this will result in a jQuery object instead of a DOM element, so you better use the length() method for checking existence.
check with .length ,coz className will give you array list if exist
var el = document.getElementsByClassName("classname");
if ( el.length > 0 ){
console.log("exists");
} else {
console.log("not");
}
You need to use getElementsByClassName instead of getElementById.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If using jQuery, please use class selector.
https://api.jquery.com/class-selector/
Try this:
if($('.classname').length > 0)
{
alert('exist');
}
You could try something like this:
if ($(".classname")[0]){ // do stuff }
This will use the jquery selector to grab all items with that class name, and attempt to access the first result (in position 0). This will fail if there are no elements with this class name.
You can use this:
var el = document.getElementsByClassName("classname");
if (el) {
console.log("exists");
} else {
console.log("not");
}
try this.this will show how to get the class in automatically document.ready or , when a button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="classname">something</div>
</body>
<script type="text/javascript">
// you can check the class name in document ready or in any other event like click
//this will show all the class names of div when document ready.
$(document).ready(function(){
var the_class_name = $("div").attr('class');
alert(the_class_name); // this put to show you the classs names
if(the_class_name == "classneme")
{
//do your coding
}
else
{
//do your coding
}
});
//if you want to get the class name when a button click and check if the class is exist
$(document).ready(function(){
$("div").click(function(){
var classnames = $(this).attr('class');
alert(classnames);
if (classnames == "your_class_name")
{
// your code here
}
else
{
// your code here
}
});
});
</script>
</html>

Getting child id using jQuery

How can I retrieve this Id using jQuery?
<span data-itemkey="40e1eec6-f949-468e-8a25-ba97d0ec3fb2" class="word">
<div class="additionalStyling green" id="2">Approval Process</div>
</span>
I tried this which returns undefined
$(document).on("click", ".word", function (e) {
var id = $(".word:first-child").attr("id");
}
Change this:
var id = $(".word:first-child").attr("id");
To:
var id = $(this).find("> div").first().attr("id");
Just to make sure, I am not copying the same one:
var id = $(this).children().first().attr('id');
As there will be multiple elements with class .word, $('.word') will return a set of elements.
Use
$(this) // The element that is clicked
.children() // Get all direct descendants
.first() // Get first element from it
.attr('id'); // Get the `id` attribute value
children accepts a selector so you can make the above shorter thus:
$(document).on("click", ".word", function (e) {
var id = $(this).children(':first').attr('id');
}
Try:
$(document).on("click", ".word", function (e) {
var id = $(this).find('[id]').attr('id');
});

Hide element which is not a certain class

I want to hide an element which is not a certain class via jQuerys not() :
Content 1
Content 2
<div class="post-item c_1"></div>
<div class="post-item c_2"></div>
and
var thisContent;
jQuery('.content-btn').click(function() {
thisContent = this.id;
jQuery('.post_item').not('.'+thisContent).fadeOut();
}
am I using .not() method wrong in this context, because it seems not to work!
Your selector needs to be
jQuery('.post-item')
And you need to close the ) at the end of your jQuery, like this:
var thisContent;
jQuery('.content-btn').click(function() {
thisContent = this.id;
jQuery('.post-item').not('.'+thisContent).fadeOut();
});
See http://codepen.io/anon/pen/EaNXjg for a working example.
Try using
$(element).hasClass(".clasname").fadeOut();
as #AND Finally noticed modify your selector .. and while you use click on Anchor you need to use e.preventDefault; try this
jQuery('.content-btn').click(function(e) {
e.preventDefault;
thisContent = this.id;
jQuery('.post-item').not('.'+thisContent).fadeOut();
$('.'+thisContent).fadeIn();
});
DEMO

how to check if div has id or not?

<div id="cardSlots">
<div class="ui-droppable" tabindex="-1" id="card1">one</div>
<div class="ui-droppable" tabindex="-1" id="card2">two</div>
<div class="ui-droppable" tabindex="-1">three</div>
<div class="ui-droppable" tabindex="-1">four</div>
</div>
<script>
$(".ui-droppable").each(function () {
if($(this).attr("id").length>0)
{
alert('here');
}
});
</script>
I am trying to loop through class but issue is i have card1 and card2 ids duplicate in that page. but above code seems to work but showing below error.
Uncaught Type Error: Cannot read property 'length' of undefined
I am trying to get ids from the loop which are there.
Use attribute selector selector[attribute] to get only the elements that have an ID
$('.myClass[id]') // Get .myClass elements that have ID attribute
In your case:
$('.ui-droppable[id]').each(function(){
alert( this.id );
});
jsFiddle demo
if(this.id) is all you need.
Why will this work?
If the element has an ID, the value will a non-empty string, which always evaluates to true.
If it does not have an ID, the value is an empty string which evaluates to false.
I am trying to get ids from the loop which are there.
To get a list of IDs, you can use .map like so:
var ids = $(".ui-droppable").map(function() {
return this.id ? this.id : null;
}).get();
or use the selector Roko suggests in his answer.
demo http://jsfiddle.net/QRv6d/13/
APi link: http://api.jquery.com/prop/
Please try this, this should help
code
$(".ui-droppable").each(function () {
if($(this).prop("id").length > 0)
{
alert('here');
}
});​
If there is no id attribute attr method will return undefined. Just write:
if($(this).attr("id"))
if(typeof $(this).attr("id") != 'undefined')
var $this = $(this);
if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) {
...
}
If you're going to use $(this) more than once, it's advised to find it once, and put the resulting jQuery object in a local variable.

How to add class to element only if it already does not have it?

How to add a class to an element only if it already does not have it? Say we don't know if the element has class="desired_class ... but we want to make sure it has.
Also, you can use classList property and it's add() method:
var element = document.getElementById('myElement');
element.classList.add('myClass');
The class name will be added only if the element does not have it.
More about classList:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
try this
var elem = $('selector');
if(!elem.hasClass('desired_class')){
elem.addClass('desired_class');
}
I wrote a JavaScript-only function that checks if the class exists before adding it to the element. (You can always use classList as mentioned here, but support for that starts with IE10.)
function addClass(name, element) {
var classesString;
classesString = element.className || "";
if (classesString.indexOf(name) === -1) {
element.className += " " + name;
}
}
var element = document.getElementById('some-element');
addClass("on", element); // Adds the class 'on'
addClass("on", element); // Ignored
addClass("on", element); // Ignored
document.write('Element classes: ' + element.className);
<div id="some-element"></div>
In plain javascript check class existence by using below code. Here I'm checking el (element) has tempClass or not
var el = document.getElementById("div1");
...
if (el.classList.contains("tempClass")){
return true;
}
if ($('element').hasClass('some_class')) {
$('element').addClass('class_name');
}
Are you sure you want to do it with JQuery only? You can do it with simple JavaScript
document.getElementById("elementId").getAttribute("class")
will give you null if the class attribute is not present.
if (!$("your_element").hasClass("desired_class")) {
$("your_element").addClass("desired_class");
}
An updated answer to this question is using toggleClass
$( "element" ).toggleClass( "className" );
http://api.jquery.com/toggleclass/

Categories

Resources