Does querySelectorAll() accept ('div.element:first') this type of argument? I need to convert below jQuery method in VanillaJS
jQUery :
$li = $(this)
$li.find('div.element:first')
Vanilla :
var li = event.target;
li.querySelectorAll('div.element:first');
But the Vanilla script is not working as same as jQuery. Someone please suggest any better solution
jQuery's :first reduces the set of matched elements to the first in the set.
In other words, you get the first element matching div.element.
To do the same in plain javascript, all you have to do is call querySelector without the All part
var first = li.querySelector('div.element');
As querySelector will return the first element that matches the specified selector anyway
This of course only works if li is a single element, querySelector doesn't work on collections the way jQuery's find() does.
If li is not a single element, you have to iterate, but since you're only looking for the first element, you could just do
var first = li[0].querySelector('div.element');
Related
How can I create a new element using just a selector? (e.g. .myclass, #myid or a:not(.someclass)) Basically there is no way for you to tell if the element is a div, span, li, an anchor, if it's a div with a class or with an id and so on.
In jQuery I know you can do $(selector) to get a usable DOM object. But how can this be done in JavaScript?
In jQuery I know you can do $(selector) to get a usable DOM object...
Not to create one. jQuery will do a search in the DOM for existing matches. You can do $("<div>") and such (note that's HTML, not a CSS selector) to create elements, but jQuery doesn't have a feature for creating elements from CSS selectors.
But how can this be done in JavaScript?
You'll have to parse the selector, and then use document.createElement with the tag name, and then set any classes or other things the selector describes on the new element.
CSS selectors aren't very hard to parse. You'll be able to find a lib that does it. (jQuery has Sizzle, which is a selector engine, built in and Sizzle is open source. It will naturally have code to parse selectors.)
Mootools does this.
new Element('#name.class')
yields
<div id="name" class="class"></div>
The answer appears to be that there is no built-in way of doing this. Maybe there’s a library which does the job.
However, it’s not to hard to write a function to create an element from a simple selector:
/* createElementFromSelector(selector)
================================================
Usage: element#id.class#attribute=value
================================================ */
function createElementFromSelector(selector) {
var pattern = /^(.*?)(?:#(.*?))?(?:\.(.*?))?(?:#(.*?)(?:=(.*?))?)?$/;
var matches = selector.match(pattern);
var element = document.createElement(matches[1]||'div');
if(matches[2]) element.id = matches[2];
if(matches[3]) element.className = matches[3];
if(matches[4]) element.setAttribute(matches[4],matches[5]||'');
return element;
}
var testitems = [
'div#id.class#attribute=value',
'div#id.class#attribute',
'div',
'div#id',
'div.class',
'#id',
'.class',
'#id.class',
'#whatever'
];
testitems.forEach(item => {
var element = createElementFromSelector(item);
console.log(element);
});
The tricky part is the regular expression. You can see it in detail here: https://regex101.com/r/ASREb0/1 .
The function only accepts selectors in the form element#id.class#attribute=value with the any of components being optional, as you see in the test items. I think including pseudo classes is probably pushing the friendship, but you might like to modify it to include multiple real classes.
I have following code in Java script from which i have to need get the value on an inner attribute of <li>.
<li class="selected" data-val="1">
I have get the tag using
var a = document.getElementsByClassName('selected');
it is providing me <li> whole tag that is fine. But i have to need get the value of data-val attribute (which is within the <li>) that is 1.
How can i get the value of data-val using variable a that is defined.
Please explain..
Here a is a collection object so you need to get the element reference using index then use .getAttribute() to get the attribute value()
var a = document.getElementsByClassName('selected');
var val = a? a[0].getAttribute('data-val') : '';
//another option for modern browsers
// val = a[0].dataset.val
Since you have jQuery, you can use jQuery to select the element and then use data api like
var val = $('.selected').data('val')
With jQuery you can use $(a).attr("data-val").
Without jQuery you can use a.getAttribute("data-val")
Try this approach
var dataValValue = $(".selected").attr("data-val");
It will get data-val attribute from first li from all li with class .selected
There are two ways, using jQuery and the first returned element in a:
$.data(a[0],"val");
$(a[0]).data("val");
Both are equivalent. Sorry, they're not equivalent, since the first one is lower level, and does not process data-* attributes by itself.
There's no need to use .attr() since data-* attributes are processed automatically in the case of the second one.
I have a jQuery statement like this;
var current = $(this);
current.hide();
current.siblings('.ab').hide();
current.siblings('.cd').hide();
I want to change this into a single statement and I wrote;
$(current,current.siblings('.ab'),current.siblings('.cd')).hide();
But ab is not hiding. How can I combine the 3 hide() statements into one?
You can use a multiple selector and addBack():
$(this).siblings(".ab, .cd").addBack().hide();
addBack() will add the original element back into the set, so you can get both the element and its relevant siblings in the same jQuery object.
You can use a multiple selector (comma separated) for the siblings function and than use addBack to include the first element.
Add the previous set of elements on the stack to the current set,
optionally filtered by a selector.
Code:
current.siblings(".ab, .cd").addBack().hide();
Try to use .end(),
current.siblings(".ab, .cd").hide().end().hide();
or use .add() like below,
current.add(current.siblings(".ab, .cd")).hide();
try this:
var current = $(this);
current.hide().siblings('.ab').hide().end().siblings('.cd').hide();
You can use comma separated multiple selectors in .siblings()
current.siblings('.cd,.ab').addBack().hide();
Working Demo
I have some HTML blocks look like
<li id="item261">
<div class="itemdesc">
<a class="icon-hide">Hide</a>
</div>
</li>
And i have a jquery like
$(document).ready(function()
{
$('.icon-hide').click(function(){
var elemId = $(this).parent().attr("id");
});
});
I need the ID of the "li" tag on click of ".icon-hide". how can i achive this? any help..
I'd suggest:
$('.icon-hide').click(function(){
var elemId = $(this).closest('li').attr('id');
});
This is because parent() as implied in the name of the method looks at the parent of the element returned by the selector (the parent is the div); whereas closest() continues up the ancestor tree to match the first selector passed to the method.
You could, instead, use parents(), however the important difference between closest() and parents() is that closest() returns zero or one match, whereas parents() will continue all the way to the root element and return every match it finds, so it can return zero, one or many matches.
Another difference is that parents() starts searching from the current element's parent, whereas closest() starts with the current element itself, so it's quite easily possible, using closest() for the method to return the current/$(this) element itself.
References:
closest().
parent().
parents().
$(this).closest('li[id]').attr('id')
Let's say that I have a DOM object:
var a = document.getElementById('parent')
I want to search all input inside element a.
What should I do in jQuery?
I want to disable all input inside a, like syntax below:
$('#parent input').attr('disabled',true);
I tried
$(a).children('input').attr('disabled',true);
but gave no results.
Note: var a is an element I got from another function.
$(a).find('input').prop('disabled', true);
children() just searches immediate children of the element while find() searches all descendants.
Update: Also consider sinsedrix's remark on the difference between attr() and prop().
Don't forget attr is for HTML attributes and prop for DOM properties, try this:
$(a).find('input').attr('disabled','disabled');
or
$(a).find('input').prop('disabled',true);
$(a).find('input').attr('disabled',true)
$(a).find('input').attr('disabled',true);