How to select element by id within existing selection? - javascript

Given HTML:
<div id="div-a"></div>
<div id="div-b"></div>
<div id="div-c"></div>
And a previously-created jQuery selection:
var $divs = $("div");
How can I select a particular div in that selection by its id?
Note: the $divs selection has not yet been appended to the DOM, so I can't just select directly (e.g. $("#div-b")).
find() selects descendants of a selection, so this does not work:
$divs.find("#div-b");
has() / :has() selects elements that contain an element with the specified selector, so this does not work:
$divs.has("#div-b");

You want to use filter() to reduce the set/.
var elem = $divs.filter("#div-b");

I think you are looking for filter():
var $subset = $divs.filter("#div-b");

If you want to only examine elements within a particular jQuery object that you've already created, you can use the .filter() method:
var $divs = $("div");
var item = $divs.filter("#div-a");
This will examine only the elements within the $divs jQuery object so see if any of them match the selector "#div-a" and will return to you a new jQuery object that contains only the matches (either zero or one object in this case).

Related

Javascript how to append an element to div with specific class

I have some <div>s where I want to append some data to a child div with a specific class but I'm not sure how to do that:
Here is my JS code:
let items = document.querySelectorAll(".item");
items.forEach(function (item) {
let textnode = document.createElement('p');
textnode.innerHTML = 'some text';
item.appendChild(textnode);
});
This actually works, bu it only appends the "textnode"-element to the existing elements.
When I try:
document.getElementsByClassName('left').appendChild(textnode);
It doesn't work.
Here is a JSFIDDLE
EDIT
I want to append the data to the .left element
It seems you want to append an element to .left descendant of item elements. If this is the case, you can use the querySelector instead of getElementsByClassName:
item.querySelector('.left').appendChild(textnode);
Note that above code calls the querySelector method as a member of item (instance of HTMLDivElement interface).
getElementsByClassName returns multiple elements. Class names are not unique. Therefore you first need to select an element in that list.
var textnode = document.createTextNode("Test");
var node = document.getElementsByClassName('left');
node[0].appendChild(textnode);
<div class="left"></div>
getElementsByClassName returns the array of elements. So u need to use the index for that.
let x = document.getElementsByClassName('left')
x[0].appendChild(textnode)
This is working.
I have updated the code in your fiddle. Please check out

Is there a way to grab an element by attribute?

I have the following custom tag/directive :
<tile class="ng-scope gridster-item" tilevalue="1" gridster-item="tile" row="0" col = "0" ng-repeat="tile in selectedTiles"> </tile>
I wanted to set focus on this element. Is there a way to get an element by attribute name, so that I can set focus?
With plain javavascript you can use .querySelector and .querySelectorAll to get the elements you want, just like in CSS.
var element = document.querySelector('[class="ng-scope gridster-item"]')
var element = document.querySelector('[gridster-item="tile"]')
Then you are free to use whatever you want with element.
as you tagged jquery, you have a lot of possibility, if there is only one element named "tile", you can use the element name $("tile"), or $(".ng-scope.gridster-item") based on classes.
Otherwise, use any attribute with $("[attribute_name='attribute_value']")
Note this can return an array of object. To get the element itself use $("[attribute_name='attribute_value']")[0] for example.
Use document.querySelector or document.querySelectorAll (no jQuery required)
var elements = document.querySelectorAll("[gridster-item]");
or:
var elements = document.querySelectorAll("[gridster-item=tile]");
Set the focus:
elements[0].focus();
querySelector returns the first element, querySelectorAll returns an array-like NodeList.

Remove element from jQuery selection

Let's say I have some sibling DOM elements that exist only within a jQuery selection:
var $container = $('<div></div><span></span>');
I want $div to only contain <div></div>, so I try to remove the <span>:
$container.find('span').remove();
// Note that span still exists:
console.log($div.length === 2);
What's the right way to solve this?
Your current selection is your <div> element. You need to find your span within there and call .remove() on that.
The parameter passed to .remove() does not find elements within the current collection, it filters it.
var $div = $('<div><span></span></div>');
$div.find('span').remove();
This doesn't modify the current selection so this isn't ideal, but I ended up finding a solution using .not():
$div = $div.not('span')

How to remove specific elements from a JQuery object which is not yet added to the DOM?

If I have a JQuery object which contains elements already being in the DOM, the remove function will properly remove them from it.
However, I would like to remove specific elements which are not yet added to the DOM, only existing in a JQuery object, like the following:
var $div = $("<div><span class='sample'></span></div>");
$div.remove(".sample");
console.log($div.html()); // prints out the original HTML, inner span is not removed
If you pass the selector to remove() then the selector will be applied to the passes set of elements in your case $div which does not contain the sample element, it is a descendant of the elements referred by $div. So you need to use .find() to find the element and remove it
var $div = $("<div><span class='sample'></span>some content</div>");
$div.find(".sample").remove();
$('#result').text($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
var $div = $("<div>outside of sample <span class='sample'>inside of sample</span></div>");
$div.find(".sample").remove();
alert($div.html());
demo: http://jsfiddle.net/3p0zsa8h/
The $div holds the jquery object and they treated as a jquery object.
var $div = $("<div><span class='sample'>4334</span></div>");
$div.find(".sample").remove();
console.log($div.html());
DEMO
Basically $div would holds the object of the wrapper div element, so by using it, you could select its descendant by using .find(selector) function and after that remove it by .remove()
Try,
var $div = $("<div><span class='sample'></span>hai</div>");
$div.find('.sample').remove();
alert($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

jquery select first child with class of a parent with class

How can i select only the first child of a particular class of a parent with a particular class for the purposes of clone()?
<div class="sector_order">
<div class="line_item_wrapper">
SELECT THIS DIV
</div>
<div class="line_item_wrapper">
NOT THIS DIV
</div>
</div>
I am trying like this:
var form1 = $(this)
.parents('.sector_order')
.children('.line_item_wrapper')
.children().clone(true)
and get both inner divs with the class line_item_wrapper, but I get an empty object when I try with this addition:
children('.line_item_wrapper :first')
Thanks!
Your problems is that your selector is wrong, in a few ways:
parents() returns one, two or many elements that match the selector passed to the method; to limit yourself to the first-matched element use closest() (which returns one, or no, elements that match the passed-in selector).
Your first use of the children() method returns both elements, since they both match the supplied selector and have the class of line_item_wrapper; you need to explicitly state which of the two you want, you can either use the :first selector (or the first() method), or the :first-child selector.
The second call to the children() method finds the children of the first element matched by the selector, which you don't seem to want.
Anyway, if you must use the parent (starting from the same $(this) element):
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first').clone(true);
Or:
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first().clone(true);
Or:
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first-child').clone(true);
Or, frankly, a simpler approach (but this does dispense with the parent class-name check):
var form1 = $(this).prevAll('.line_item_wrapper:last');
Or:
var form1 = $(this).siblings('.line_item_wrapper').eq(0);
References:
closest().
eq().
find().
:first.
:first-child.
first().
:last.
parents().
prevAll().
siblings().
You're passing an invalid selector to children().
Instead of
.children('.line_item_wrapper :first')
try
.children('.line_item_wrapper').first()
Use :first-child
var form1 = $(this).closest('.sector_order').find(':first-child');
OR .first()
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first();
Try this:
var $firstDiv = $(".sector_order > .line_item_wrapper:eq(0)");
This will get you the first direct descendant of sector_order with the class line_item_wrapper.
Example fiddle

Categories

Resources