Using two getElementByIds - javascript

Is it possible to do something like:
this.getElementById('first-id').getElementById('second-id')?
When I do this, I get an error "getElementById(...).getElementById is not a function.
The reason I'm trying to do this is because I am able to console log the first-id element, but not the second (when I do this.getElementById('second-id')). I assume it is because my DOM is not completely loaded.
However, I thought since it loaded the first-id element, I'll be able to do another getElementById as the first part is loaded and the next element is nested/a child of the first-id element.
Can someone explain why this logic doesn't work?

An element with a given ID is supposed to be absolutely unique in a document. There should never be more than one element with the same ID. So, calling getElementById on an element to search among its children, if it were possible (which it isn't), wouldn't make a whole lot of sense - instead, search from the whole document. You should only need
document.getElementById('second-id')

Most answers here are correct and will help the OP implement the solution. This will try to answer Is it possible to do something like:, which is what OP asked originally:
this.getElementById('first-id').getElementById('second-id')
getElementById() is a Document interface method and is only available on the Document object. It is not available on the Element, and this.getElementById('first-id').getElementById will be equal to undefined. undefined is not a function and can't be invoked, hence the error.
It makes sense that getElementById() is only available in the Document interface as an ID is (ideally) supposed to be a unique in the DOM. So, providing the function inside other elements is not as useful.
querySelecetor() is both a document and element method and is available on both the objects.
That is why you can do something like :
document.querySelector('#first-id').querySelector('#second-id')
(Searches for #second-id child of #first-id)

You could possibly chain it using Document.querySelector(), but you should never need to use this as ids should be unique.
E.g, something like this:
var selected = document.querySelector('#first-id #second-id');
console.log(selected);
<div id="first-id">
<div id="second-id">1</div>
</div>
<div id="second-id">2</div>
<!-- Don't use duplicate ids - this is just for demonstration -->

You could do something weird like the following, but it's silly.
<script>
window.addEventListener("load", function() {
alert(document.getElementById("parent").ownerDocument.getElementById("child").textContent);
}, false);
</script>
<div id="parent">
<div id="child">Yo</div>
</div>

Related

How do I select and click with javascript on dom element without id?

I've got some html and this html conatains somewhere deep in the dom the following div:
<div class="barbottomleft arrow " onclick="go('login')">
As you can see there is no id or whatever and it is a div among a lot of others. However, the onclick="go('login')" makes it unique in the whole document. Therefore I'd like to select it somehow and the click on it. Something like:
javascript:document.getElementById(\"element_id\").click();
However, this is not possible since it got no id but a unique onclick function call. So is there a possibility to select this element based on the function it is going to call?
You could use a query selector with a lot of accuracy as such:
var myElement = document.querySelector('.barbottomleft.arrow[onclick="go(\'login\')"]');
This gets you an element with the two class and matching onclick attribute value. You could make it even more accurate by making sure it's a div:
var myElement = document.querySelector('div.barbottomleft.arrow[onclick="go(\'login\')"]');
I hope that helps.

Get a jQuery element for a DOMElement

I know how to do the opposite. Getting a certain DOMElement for a jQuery element is easy. (Use the get() method)
But how can you get a jQuery element for a specific DOMElement?
Unfortunately this DOMElement does not have any attributes like class or id so constructing a selector is not really an option.
Lets say I have this html:
<div class="edit">Abcd<b><i><u>asdasd</u>adasda</i></b>sdfsdf<br>asd</div>
I am in the u-DomElement. How can I get this as a jQuery element?
Is there a smart way to do this?
EDIT:
I wanted to know if there is a gerneral way to do this. Not specific to the code shown above.
Like:
DomElement.toJQuery()
Is there anything like that? I am aware that this might not be possible.
Getting a jQuery object for a DOM object is as simple as jQuery(dom_node) (or $(dom_node)). See http://api.jquery.com/jQuery/
This is commonly used in event handlers, which are given the DOM node as this, so that you will often see $(this)
If you want to get just the Element use the below code. if you wanted to get the HTML of any element you might want to add the .html() tag to either of the examples
var myVar = $('.edit u');
or
var myVar = $(".edit").find("u");
Are you looking for this?
$(".edit").find("u");
hope this is what you are looking for,
$(DomElement)
you want a only 1 specific dom element i suggest you find a way to add an id to that element.
but to get an u element inside a edit class:
$('.edit u');
$('.edit').find('u');

Find the child of the element represented by "this" that has a certain class

I know how to accomplish this if I can identify this element using a selector:
$("selector.class")
But what if my selector is the keyword this? Obviously $(this".class") isn't going to work, and I don't want to use $(this).children(".class") because then I need to extract the HTML of the element using .html(), and while I know that there will only be one element of this class in the selected element (I'm writing the HTML), JQuery doesn't, and it assumes that children() returns several elements when used with a class (at lease I think that's what it does, because
$(this).children(".class").html()
returns undefined).
Is there an other way I could do this?
Please feel free to ask for clarification, I understand this may not seem clear to some.
EDIT: some of you asked for clarification, so here it is. Let me rephrase the question: normally, when I ask JQuery to get me some elements, and give it a class as a selector it assumes I will get more than one element back and therefore $(".selector").html() doesn't work, because you can't get the HTML of several elements (at least that's my theory). Instead, I want it to recognise that in this case I am only getting 1 element back, and treat is as such. My restriction is that part of my selector is this. I hope that helped!
It isn't entirely clear to me what question you're asking so here are several different options:
To search for any subordinate tags (in the DOM tree with this as its root) that match a desired selector:
$(this).find(".myClass");
Or, if you're just trying to see if the this element has a particular class name, you can use:
if ($(this).hasClass("myClass")) {
// this element has the desired class
}
or, if the selector is more complicated than just a class, you can use .is() like this:
if ($(this).is("selector")) {
// this element matches desired selector
}
Really this isn't a selector, but I think you can do:
$(".class", this)
This is an example of supplying the context argument to the jQuery ($) function
For example (jsfiddle here),
HTML:
<div id="dis">hello
<div class="cls">
hi</div></div>
<div class="cls">
goodbye</div>
jQuery:
$(function () {
$('#dis').click(function () {
alert(
$('.cls', this).html());
});
});
will alert "hi" when the "dis" div is clicked.
Jquery is just a layer on top of JavaScript.
Just use raw javascript to get what you're looking for.
var childOfThis = this.querySelector('.myClass');

Does jQuery remove function really remove Dom elements?

I am really wondering if jQuery remove function really remove elements from DOM.
First, I looked here but the answers are not convincing.
I encountered this problem when I noticed I am still able to manipulate elements on which I have called remove function.
My code:
<div id="container">
<div id="div">
This is a div
</div>
</div>
var div = $('#div');
$('#div').remove();
$('#container').append(div);
Note: My question is not how to solve this? but I want to understand what's going on here!
Actually, this code doesn't remove the #div from the dom, but if I have any data set to the #div, it will be lost. I am pretty confused now about the behaviour of remove function. Can anyone explain this please?
DEMO
I am convinced that div variable is not just a clone of the dom element, is a reference to it, because when I manipulate the div variable, (like div.html('something')) the div within the DOM get updated.
Or am I wrong?
remove() does indeed remove the element from the DOM.
However in your example, the element has been cached in memory because you assigned it to the div variable. Therefore you can still use it, and append it again, and it will still contain all the events the original did.
If what you say is right, why I loose the data bound to the div so?
If you check the source for remove() you'll see that it calls the internal cleanData function which removes the events and clears the data cache for the element. This is why you lose the information.
If you want to remove the element from the DOM, but keep the elements, use detach() instead.
Here's a fiddle to show the difference: http://jsfiddle.net/2VbmX/
had to delete the assigned variable:
delete div;

Passing Multiple Inner Child Node to Function

I need to pass the contents of an inside div to a function, for example myfun(string). I have tried using
myfun((this).children[0].innerHTML)
myfun((this).children[1].innerHTML)
myfun((this).children[0].children[0].innerHTML)
but none of those seem to work. I can't just pass the getElementById value because the function should be generic since it would be called by php on various <a> elements (ideally I think it should include the this. keyword).
Thanks for any help.
If you don't need it to work cross-browser, there's:
this.getElementsByClassName('label')[0]
This will fail in IE 8 and below.
If you're absolutely certain the HTML/DOM structure won't change, you could perhaps use:
this.nextSibling.children[0];
But this might have issues in browsers that consider textNodes as childNodes
in your function, "this" refers to the link, and can't be used.
a much cleaner solution would be to have myfunc know that it is going to receive an object which contains the text
javascript:
myfunc(obj){
alert(obj.childNodes[0].nodeValue);
}
html
click
<div id="target">target contents</div>
The object this will apply to the <a> tag that it calls. You need to call the parent div first and then select the children accordingly.
Try using this.parent.children[1].children[0].innerHTML
Try
this.parent.children[1].children[0].innerHTML
But you should really use dynamic IDs instead of this mess.

Categories

Resources