The question is really confusing but I'll try to explain here.
In CSS I know you can say "if this DIV has x and y and z inside it in any way" then apply this style. Like
div.class id class { style }
I was wondering how I would go about doing this in Javascript for detecting the last child.
Such as getting if
div div:nth-child(2) span a
is the last child of a certain div in Javascript.
I hope this is not too confusing because it sure looks confusing to me... If you need clarification please ask.
I am going to post an answer despite the previous one, because I refuse to use (and intend to try to convince others to stop using) w3schools.
So, a much better resource: MDN - lastChild
And inline:
var tr = document.getElementById("row1");
var corner_td = tr.lastChild;
As a bonus, and in sync with the above w3fools
1) Try this by jquery
$(document).ready(function () {
var list = $("#containerId").children();
var lastElement = list[list.length - 1];
});
OR
2) pure javascript
var list = document.getElementById('containerId').children;
var lastElement = list[list.length - 1];
I think you are loking for lastChild property
Related
I'm relatively new to jQuery and need to perform some transformations on the following working code:
jQuery('#vari_1').click(function() {
var selected = [];
jQuery('#cartsnitch')
.addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val())
.fadeIn('5000');
})
The code returns the value of a radio button clicked in a tab id of #vari_1.
The problem is I then need to replace hyphens of the radio button value with spaces (duck-egg-blue to duck egg blue) and prepend an h2 heading. Chaining these appears to break my code.
I instead tried the below to make it into a variable so I can work with that on a new line, but couldn't get it to work. Can someone point me in the right direction please?
jQuery('#vari_1').click(function() {
var selected = [];
var cart1 = jQuery('#cartsnitch')
.addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val())
.fadeIn('5000');
var cart2 = ('<h2>My heading</h2>') + cart1;
return cart2;
})
It's driving me nuts! Thanks in advance.
It sure can seem daunting Utkanos, I'm yet to get a straight answer to a question after being a member for a good few years. All I seem to attract is ambiguity and politician style question dodging!
Anyway due to lack of a hint other than Ashkay's syntax error spot (not in my code sorry), I fixed it as such:
jQuery('#vari_1').click(function() {
var selected = [];
jQuery('#cartsnitch').addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val().replace("-"," "))
.prepend('<div class="mystyle"><small>My Label:</small><br />')
.append('</div>')
.fadeIn('5000');
})
val().replace() prepend() and append() were all I was after.
Thanks for the reassurance anyway!
Reason for doing that: I'm debugging css of my webpage.. some elements appeared and they're not supposed to appear. I suspect it is the issue with element positioning.. therefore I want to find these positioned element and check one by one.
This one is using jQuery. I hope you are find with it.
var find = $('*').filter(function () {
return $(this).css('position') == 'fixed';
});
I think this one works using a pure javascript:
var elems = document.body.getElementsByTagName("*");
var len = elems.length
for (var i=0;i<len;i++) {
if (window.getComputedStyle(elems[i],null).getPropertyValue('position') == 'fixed') {
console.log(elems[i])
}
}
Here is an ES6 version that gives you an array of these elements for further processing:
let fixedElements = [...document.body.getElementsByTagName("*")].filter(
x => getComputedStyle(x, null).getPropertyValue("position") === "fixed"
);
document.querySelector('*[style="position:fixed"]')
The * item specifies all tag names. The [] indicate that you're looking for an attribute. You want your style attribute to have position:fixed.
If you aren't using jQuery, this is probably going to be your simplest option.
Warnings that apply to all answers:
This is a slow operation. On a large-enough page, this operation can take 100ms or more, which is a lot for a single operation. You shouldn't need this unless you're developing a browser extension.
Now sticky elements can act as fixed elements in some cases
Having said that, here's the shortest and most efficient version to do this:
const fixed = [].filter.call(document.all, e => getComputedStyle(e).position == 'fixed');
Here's a version that includes sticky elements, but they're not exactly equivalent, it depends on what you're looking for:
const all = [].filter.call(
document.all,
e => ['fixed', 'sticky'].includes(getComputedStyle(e).position)
);
If you're feeling modern, replace document.all with document.querySelectorAll('*'), but the former will likely work forever.
Try this:
var elements = $('*').filter(function () {
return this.style.position == 'fixed';
});
It will give you all elements having position fixed.
I am trying to find if a class exists and if not just find the first form element. How do I write :input? This does not seem to work.
$('.focus:not(:hidden):first, :input:not(:hidden):first').focus();
Comma-separated selectors are not hierarchical in the manner you seem to indicate. Your selector will yield the first visible .focus and the first visible input element. You'll need to break this up in two selectors:
var focusElement = $('.focus:visible:first');
if(focusElement.length == 0)
focusElement = $(':input:visible:first');
focusElement.focus();
Or I suppose you could write
$('.focus:visible:first, body:not(:has(.focus:visible)) :input:visible:first').focus();
Your code actually worked for me. Take a look at this jsfiddle. Try removing my class='focus' and it then falls back to selecting the first input field.
I would go for the easy to understand model:
var finder = $('.focus:not(:hidden):first');
finder = finder.length ? finder: $(':input:not(:hidden):first');
finder.focus();
Same result, but likely better given the right to left sizzle re: performance
var finder = $('.focus').not(':hidden').eq(0);
finder = finder.length ? finder: $(':input').not(':hidden').eq(0);
finder.focus();
contenteditable div
((grade >= passingMark) && (grade<101))
HTML
<span class="cond frag">(<span class="cond frag">(grade >= passingMark)</span> && <span class="cond frag">(grade<101)</span>)</span>
How would i know if i am the last child of cond or there is no next sibling following me (grade<101)
Something like (in a loop):
$elem = $('.frag').eq(fragNum);
if ($elem.nextAll('.cond').length === 0 ) {
alert('last child detected');
}
If by "How would i know ..." you mean "In JavaScript, how would I get..."
MooTools makes it easy:
var last = document.getElement('.cond').getLast('span');
In this case, document.getElement will get the first element that matches .cond in document.
There will be a simple jQuery equivalent too.
If you are using native JS, you run into problems as there is no native support for "getElemntByClassName" in IE<9. There are a bunch of frameworks and tools to bridge these browser gaps like MooTools, JQuery, Prototype, etc, but if you need native and know the index position of the span with class .cond within a specific container, you could try:
var conds = document.getElementsByTagName("span")[0].getElementsByTagName("span");
var last = conds[conds.length-1];
Where document is your specific container and 0 is the position (first in container).
If this is the only problem you would like to solve, there is this 2008 "getElementsByClassName" solution that still works nicely is IE<9 by Robert Nyman - http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/
Do you mean something like this?
http://jsfiddle.net/KyleMuir/nujr7/1/
var elements = document.getElementsByClassName('cond');
var totalElements = elements.length;
var lastElement = elements[totalElements -1];
Added console.logs to illustrate this clearer in the fiddle.
Hope this helps.
I've been working on the modification of an iframe using javascript. The iframe contains this form
What I want to be able to do is retrieve information from the label; however it doesn't have an ID. is there any way I could get javascript to get the input button by ID, and have it analyze the label assigned to it?
You could go through all label elements and find the one whose for attribute matches your button ID:
var labels = document.getElementsByTagName('label');
var label = null;
var buttonID = '...';
for (var i = 0; i < labels.length; i++)
if (labels[i].htmlFor == buttonID) {
label = labels[i];
break;
}
// "label" now refers to the label you're looking for
casablanca's way is the best way if you only know the button ID.
Depending on what else you might know, other things might be quicker. If, for instance, you know that it is inside a DIV that you know the ID of, and you know that it is the only label inside that DIV, then you could do something like
var label = document.getElementById('myDiv').getElementsByTagName('label')[0];
If you know that it'll always be the only label with the same parent as your button, you could write
var label = document.getElementById('button').parentNode.getelementsByTagName('label')[0];
Basically, a broad set of solutions might be optimal depending on what assumptions you can afford to make. If you only know what you've told us in the question, then casablanca's iteration is the way to go.
I highly recommend investigating jQuery for this sort of manipulation. I'm sure that you probably don't want to introduce a whole Javascript framework to solve this one little issue, but if you learn it you will find that Javascript programming becomes much easier.
Assuming that #casablanca's answer is correct, you could accomplish the same thing in jQuery with the following code:
var label = $('label[for="..."]').get(0);
(Or something like that. My syntax may be off. :-)