According to here, jquery's remove function should work like so..
$('div').remove('selector');
Which I'm trying in this example.
HTML:
<div class="wrapper">
<p class="unwanted">This should be removed</p>
<p class="retained">This will remain</p>
</div>
JavaScript:
jQuery(document).ready(function($) {
$('div').remove('p.unwanted'); //not working
//$('p.unwanted').remove(); //this works
});
It's not working. What am I doing wrong?
You've misunderstood what the documentation is saying. It's not looking for elements that are descendants of the matched elements that match the selector, it's simply filtering down the set of already matched elements to those that match the selector, and then removing them.
If you have this HTML:
<div class="wanted">Some text</div>
<div class="wanted">Some more text</div>
<div class="unwanted">Some unwanted text</div>
and then executed this jQuery:
$('div').remove('.unwanted');
then it would only remove that third <div> (the one with the unwanted class on it), because it first selects all <div> elements, and then only removes those that match the selector.
Example jsFiddle
You're trying to remove something that is both div and p.unwanted. The filter in remove() is applied to the current set of nodes, which in this case is all div elements.
Use the children set instead:
$('div').children().remove('p.unwanted');
You should use the following:
$('p').remove('.unwanted');
Argument in remove works as a filter. So here, you first select all <p> elements and then remove only those which have class unwanted.
DEMO: http://jsfiddle.net/qwXSw/1/
try this
$(document).ready(function() {
$('div').find('p.unwanted').attr('class', '');
});
Related
I'm trying to simply get all of the first divs while exlcuding the second divs:
<div class="_5pcr userContentWrapper">
<div class="_5pcr userContentWrapper _4nef">
I searched and fout of that the querySelector function should be doing the job. However I tried it with multiple inputs, but all of those result in an empty list. If I use the DOM function getElementsByClass it works but then of course I got all divs, also the second ones that I don't want.
Here are the querySelector function calls I tried:
listOfPosterName = document.querySelectorAll('div._5pcr userContentWrapper:not(._4nef)');
listOfPosterName = document.querySelectorAll('DIV._5pcr userContentWrapper');
listOfPosterName = document.querySelectorAll('_5pcr userContentWrapper:not(_4nef)');
listOfPosterName = document.querySelectorAll('DIV.userContentWrapper:not(_4nef)');
I have even tried to just get the same result as with "getElementsByClass('_5pcr userContentWrapper')" with this:
listOfPosterName = document.querySelectorAll('_5pcr userContentWrapper');
That also did not work. I thought it's a problem because of the space between the classes, but I tested it also with a single class.
I really appreciate help!
Your problem is just putting too much spaces where unnecessary:
listOfPosterName = document.querySelectorAll('._5pcr.userContentWrapper:not(._4nef)');
You are not writing the selectors correctly.
When you want to select an element having multiple classes you would do:
document.querySelectorAll('.class1.class2.class3');
When you leave a space character in a selector - it becomes what is called a descendant selector. Example:
<div class="class1">
<p class="class2"></p>
</div>
In this case, class2 could be selected with a descendant selector:
document.querySelector('.class1 .class2');
Your fixed example could look like so:
<div class="_5pcr userContentWrapper">
<div class="_5pcr userContentWrapper _4nef">
document.querySelectorAll('._5pcr.userContentWrapper:not(._4nef)');
querySelector() works just fine, but you have to pass it the selector properly. Multiple classes should be concatenated together, not space separated like in the HTML.
document.querySelector("._5pcr.userContentWrapper").classList.add("selected");
.selected { background-color:yellow; }
<div class="_5pcr userContentWrapper">Me</div>
<div class="_5pcr userContentWrapper _4nef">Not Me</div>
I want to remove some silblings. I tried as given below.
But not working. why? And how to solve it?
<div>
<div id="idx1">child1 </div>
<div id="idx2">child2</div>
<div id="idx3">child3</div>
...
<div id="/a/b/c">This should be last child</div>
<div id="idx4">Remove it.</div>
<div id="idx5">Remove it.</div>
<div id="idx6">Remove it.</div>
...
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// Since the id contains special chars,
// javascript method has been used to get the element.
lastChildObj = jQuery(document.getElementById('a/b/c'));
// I don't know how to remove the childs after lastChildObj.
// I tried as given below.
lastChildObj.filter('~').remove();
There are two key steps to this.
Select the elements to remove
Remove them
Step 1 can be broken down into two parts, obtaining a reference to the last element to keep, then getting a list of all of its siblings that come after it. Step 2 just uses the .remove() function.
$(document.getElementById('/a/b/c')).nextAll().remove();
You can still use jquery for your selector but you need to escape the id like so :
$("#\\/a\\/b\\/c")
Then you just need to select any following divs like this :
$("#\\/a\\/b\\/c").nextAll().remove();
http://jsfiddle.net/8mMJq/
Further informations about special characters in selectors : http://api.jquery.com/category/selectors/
This should work for you:
var base = document.getElementById('/a/b/c');
while(base.nextSibling){ // While the element has siblings
base.parentElement.removeChild(base.nextSibling); // remove the siblings from the parent element.
}
Working example
You can also make it slightly more efficient:
var base = document.getElementById('/a/b/c');
while(base.parentElement.removeChild(base.nextSibling)) // Remove the nextSiblings while they exist.
Example
Try this :
$("#\\/a\\/b\\/c").nextAll().remove();
JsFiddle : http://jsfiddle.net/QcvWQ/
First of all change id from "/a/b/c" to ie "abc" and then run following
$("#abc").nextAll().each(function () { $(this).remove());});
So I have a div with some child elements and when I select one with jQuery I want to get the index of it within a selector
<div>
<div class="red"></div>
<div class="red"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="blue"></div>
<div class="red"></div>
</div>
So lets say that I have the last element in the main div selected. If I call index() on it it will give me '7' because out of all the child elements the index is '7'. But now lets say I want to get the index based on the other 'red' elements, the goal is to return a value of '4' because out of all of the 'red' elements it is the fifth one. I looked through the documentation and didnt find a whole lot, then I experimented with putting selectors in the index() method like index('.red') but I couldn't get anything working.
Well, the documentation says:
.index( element )
element The DOM element or first element within the jQuery object to look for.
So can do:
selectedElements.filter('.red').index(this);
If you don't have selectedElements already, you can select corresponding siblings with, for example:
$(this).parent().children('.red')
If every element has only one class and then the filter can be dynamic:
var index = $(this).parent().children('.' + this.className).index(this);
Use the .index() function documented here
For the above if one wants to get the index of a element of the red class use $('div .red').index(elem);
$('div .red) will create a list of the elements with the red class within the div. .index(elem) will search for the elem within the array.
Running through all of them using id=test as parent
DEMO : http://jsfiddle.net/T7fXR/
$('#test > div').each(function(){
var thisClass=$(this).attr('class');
$(this).css('background',thisClass );
/* get index based on class*/
var idx=$('.'+thisClass).index(this);
$(this).text('Index= '+idx)
})
For me, this works just fine with your given HTML:
$('div').eq(5).index('.red') // 3
You can place selectors into the .index() function.
I want to append some text after 2 closing divs to a sector element.
Click me
</div>
</div>
// this is where I want to append the text
My code appends the text after the link. How can I say "append it after the 2nd closing div"?
$('a.thingIClicked').click(function() {
$(this).append('hello');
});
The most direct way to do this is to find the second parent <div> element, and then insert the text after it.
$('a.thingIClicked').click(function() {
$(this).parent("div").parent("div").after("some text");
});
This will insert the text on the outside of the second <div> parent. Using append() will put the text on the inside of the parent, which from your example doesn't appear to be what you want.
There's probably a more elegant solution, but how about:
$('a.thingIClicked').click(function() {
$(this).parent().parent().after('hello');
});
Edit: #Zack is correct (and should probably get the answer credit for this one) - my original code would have added the text into the second enclosing div, rather than after it. I've edited my code above accordingly.
The easiest way would be to give the outer div an id and then use $("#outerdivid").
EDIT: Below will not work, but leaving it here for reference
However, you should also be able to use a jquery :parent filter:
http://api.jquery.com/filter/
$('a.thingIClicked').filter(':parent').filter(':parent').click(/**/);
Use .insertAfter()
http://api.jquery.com/insertAfter/
<div class="container">
<h2>Greetings</h2>
<div>Hello</div>
<div class="inner">Goodbye</div>
</div>
We can create content and insert it after several elements at once:
$('<p>Test</p>').insertAfter('.inner');
Use .insertAfter() - http://api.jquery.com/insertAfter/
<div class="container">
<h2>Greetings</h2>
<div>Hello</div>
<div class="inner">Goodbye</div>
</div>
We can create content and insert it after several elements at once:
$('<p>Test</p>').insertAfter('.inner');
It works:
<div class="xpav">
Create
</div>
<div class="apr" style="display: none;">
sometext
</div>
<script>
$('.xpav').click(function() {
$(this).next(".apr").slideDown("fast");
})
</script>
It doesn't:
<div class="xpav">
Create
</div>
<br />
<div class="apr" style="display: none;">
sometext
</div>
<script>
$('.xpav').click(function() {
$(this).next(".apr").slideDown("fast");
})
</script>
Why breaks it?
.next() only looks at the element that comes after the given element, then checks that element against the selector if it's provided. In your second example, since the br is there and doesn't have the apr class, it isn't picked up. From the API docs:
Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Your second example requires the use of .nextAll() instead to search through all the next siblings:
$('.xpav').click(function() {
$(this).nextAll(".apr").slideDown("fast");
});
To pick up only the first .apr that's matched, use .eq(0):
$('.xpav').click(function() {
$(this).nextAll(".apr").eq(0).slideDown("fast");
});
under my impression next() only works if the sibling objuect is the same DOM tage,
what does work is:
$('.xpav').click(function() {
console.log($(this).next(".apr"));
$(this).siblings(".apr").slideDown("fast");
})
It's exactly that what the documentations says: "Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector."
http://api.jquery.com/next/
Because next() takes you to the immediate next DOM element which is <br />. Why not use this:
$(".apr").slideDown("fast");
Simply because you are using the next() method in your code. The next DOM element from $('.xpav') in the second version of your code is a <br />, and since that doesn't match the filter, it doesn't slide anything down!
If you want it to work, you should consider using nextAll() instead of next(), as the latter ONLY gets the very next DOM element, where the former gets all siblings that are after itself in the DOM.