Jquery find all except - javascript

I have following HTML:
<div id="123" class="test">
<div class="testMessage">Foo</div>
<div><div class="testDate">2010</div></div>
<div id="127" class="test">
<div class="testMessage">Bar</div>
<div><div class="testDate">2011</div></div>
</div>
</div>
And I have following JS/jQuery code:
$(".test").find(".testDate").val("cool 2010");
How to change JS/jQuery to find "testDate" class element except in children "test" class block without using children?
P.S. I know only about class name and I don't know how many divs can be nested.

Update
Its probably the weirdest selector I've ever written:
$("div.test").not(':has(> .test)').siblings().find('.testDate').text('cool 2010');
Demo: http://jsfiddle.net/mrchief/6cbdu/3/
Explanation:
$("div.test") // finds both the test divs
.not(':has(> .test)') // finds the inner test div
.siblings() // get all other divs except the inner test div

Try this and also div elements do not have a value property, use html() method to set the inner html or text()
$("div.test :not(.test)").find(".testDate").html("cool 2010");
If you can modify your main div id to "_123", you can straight away use the id selector like this
$("#_123 > div.testDate").html("cool 2010");

I think the not() selector might help. You can learn more about it here: http://jsperf.com/jquery-css3-not-vs-not

Anytime you try to select $('.test'), it will grab all elements with a class='test'. You need to start at the outermost body tag:
$('body').children('.test').children(':not(.test)').find('.testDate').text('cool 2010');

Related

How do I access a sub-element when using $(this) in jQuery

I have the following code:
$(document).ready(function(){
$(document).on('click', '.mydiv', function(){
console.log(??????);
});
});
I also have the corresponding html
<div class="mydiv">
<p>Hello from inside a mydiv</p>
</div>
<div class="mydiv">
<p>Hello from inside some other mydiv</p>
</div>
My goal is to print the text inside the p tags to the console when the I click on any div with the class of mydiv. I know that this means I should be using the $(this) operator, but when I do that I am unsure of how to then access its sub elements.
I know if I were using id's (or if I only had one of these class objects) I could simply do $('#mydiv p').val(), but I'm unsure of how to achieve this when I'm using $(this).
You can use $('p',this) or $(this).find('p') to get p tag element in this context:
$(document).on('click', '.mydiv', function(){
console.log($('p',this).text());
});
Working Demo
Using $(this) and jQuery's .find() you can get the child elements that you choose:
console.log($(this).find('p').html());
There are multiple ways to go about this. One of the ways has been mentioned here by others (the find method). The problem with the find method is that it finds all elements inside your div and not the direct children. So, if you have elements that are nested another level, it gets that as well.
With the children method, it will find the direct child of the element, but not anything nested deeper.
<div class="mydiv">
<div>
<p>Nested p</p>
</div>
</div>
$('.mydiv').find('p'); // Finds this element, but children() will not
Versus
<div class="mydiv">
<p>
Direct p
</p>
</div>
$('.mydiv').children('p'); // Will find this element, but find() will as well
With the find method, you will find the one nested inside the second div, whilst with the children method, you will find only the direct child.
Depending on your needs, you may use find or children

Find the first parent of a selector

Consider this sample html
<div class="A">
<div class="B">
<span class="C">Sample text</span>
<div class="D">
<div class="E">Clickable Text</div>
</div>
</div>
</div>
And some jQuery
$(".E").click(function(){
//body
});
What is the easiest way to get a parent of $(this) that matches a selector? For example, say in the example I need to get the div where class="A". At the moment because I know the structure of the html I could do
$(this).parent().parent();
But I'm looking for a way that would work regardless of the structure. Something along the lines of
$(this).findFirstParent(".A");
I hope I've been understandable.
$(".E").click(function(){
console.log($(this).closest('.A'));
/* console.log($(this).parents('.A')); works fine too */
});
See
http://api.jquery.com/closest/
http://api.jquery.com/parents/
Note that parent() is different than parents() method (the first one look for one ancestor only)
First Solution:
$(this).closest('.A')
Source: http://api.jquery.com/closest/
This will return the first parent when traversing that matchs the selector.
Second solution:
$(this).parents('.A:first')
Source: http://api.jquery.com/parents/
This will return all the parents that matches the selectors
What about
$(this).closest(".A");
This is the way i would do it
$(this).parents("div.A")
The jQuery parent selector might help you there. You can combine it with the class you are looking for. See the docs #
http://api.jquery.com/parent-selector/

How to select an element by ID using jQuery

I am trying to use the following jQuery code to add a div with class col_box inside the col_left div:
$('#col_left').add('div').addClass('col_box');
My DOM tree looks like this:
<div id="header">Header</div>
<div class="col_container">
<div id="col_left">
<div class="col_box">A</div>
<div class="col_box">B</div>
</div>
</div>
However the jQuery code isn't working. It adds the class col_box to every element on the page.
$('#col_left').add('div') is adding all <div> elements to the original selection. Try using $('#col_left').append('<div class="col_box"></div>') instead (or .prepend).
$('#col_left').add('div') means the same as $('#col_left, div'). i.e. "The element with the id 'col_left' and all div elements.
If you want to select the divs that are children of col_left, just use a child combinator.
$('#col_left > div').addClass('col_box')
.add() adds a selector to the selection, it doesn't create or add elements.
$('#col_left') means *select element id col_left*
.add('div') means add all divs of the page the the selection
So at this point you've selected #col_left and all the divs.
.addClass('col_box') means *add the class col_box to all elements of the selection*.
Here is how to create a div and add it to #col_left:
$('<div></div>').addClass('col_box').appendTo('#col_left');
Or:
$('<div class="col_box"></div>').appendTo('#col_left');
you can use
.append appends after the matched target
$('#col_left').append(
$("<div/>",{class:'col_box'}).html("div added")
);
here is the fiddle http://jsfiddle.net/R65cn/4/

Is it possible to get a selector using indexOf

Like
<div id="box_1">
<div id="box_2">
<div id="box_3">
If i want to get all id's starting with 'box_' how can i do it something like this..
$("#box_" + anything )
Unfortunately wrapping the div's won't work because it will get all the other divs in side and between the box divs.
I guess i can give them all another class and reference it like that, but just wondering if there's something like this out there.. thanks.
You can use an Attribute Starts With selector:
$("div[id^=box_]");
It is possible with the attribute starts with selector as others have mentioned, but it might be better to give each element a class:
<div id="box_1" class="box"></div>
<div id="box_2" class="box"></div>
<div id="box_3" class="box"></div>
Select with:
$(".box")
Yep:
$('div[id^="box_"]');
In this case, because you are trying to use the ID selector, its better to switch to an element selector, combined with an attribute selector.
You can use an attribute selector:
$('[id^="box_"')
That will give you all elements whose id starts with "box_". If you need to, qualify it with an element:
$('div[id^="box_"')
If you dont know whether it starts or endswith any string then you can try *= selector which will look within the attribute value.
$("div[id*='box_']");

Remove attribute of HTML tag

Is it possible to remove the attribute of the first HTML <div> tag? So, this:
<div style="display: none; ">aaa</div>
becomes
<div>aaa</div>
from the following:
<div style="display: none; ">aaa</div>
(bbb)
<span style="display: none; ">ccc</span>​
Or pure JavaScript:
document.getElementById('id?').removeAttribute('attribute?')
To remvove it from literally the first element use .removeAttr():
$(":first").removeAttr("style");
or in this case .show() will show the element by removing the display property:
$(":first").show();
Though you probably want to narrow it down to inside something else, for example:
$("#container :first").removeAttr("style");
If you want to show the first hidden one, use :hidden as your selector:
$(":hidden:first").show();
Yes, in fact jQuery has something for this purpose: http://api.jquery.com/removeAttr/
You can use the removeAttr method like this:
$('div[style]').removeAttr('style');
Since you have not specified any id or class for the div, the above code finds a div having inline style in it and then it removes that style from it.
If you know there is some parent element of the div with an id, you can use this code instead:
$('#parent_id div[style]').removeAttr('style');
Where parent_id is supposed to be the id of parent element containing the div under question.
You say "remove the attribute" — do you mean to remove all attributes? Or remove the style attribute specifically?
Let's start with the latter:
$('div').removeAttr('style');
The removeAttr function simply removes the attribute entirely.
it is easy in jQuery just use
$("div:first").removeAttr("style");
in javascript
use var divs = document.getElementsByTagName("div");
divs[0].removeAttribute("style");

Categories

Resources