javascript : add some content in parentNode - javascript

What could be best way to add some content into ParentNode, if it has several child nodes without id.
the condition are :
<div class="parent_div">
<div class="child_div_1" > I need to add contents inside this div </div>
<div class ="child_div_2" onmouseover="addClass(this)"> </div>
</div>
My possible solution : function addClass(obj) {
obj.parentNode.firstChild.appendChild(...);
}
But i have doubt if someone changes the position of first child then what? according to you what could be best way to sort out this problem.

Use JQuery :
function addClass(obj) {
$(obj.parentNode)
.find("ClassName_in_which_you_want_to_append")
.append("your_derived_contents");
}
Note : find() it just look up the class_name whatever you want. Position doesn't matter. It just look up inside the parent node.
append() : just add the contents as a child
I hope this helps you a lot.

I'm not sure I understand. There must be something determining which element you want to put the content in and, if that's the case, it should have an ID (a unique element deserves a unique field, right?)
If those class names that you've defined (child_div_1) are meaningful to the element in which you need to insert content, you can use the method getElementsByClassName to select the correct element.
function addClass(obj) {
obj.parentNode.getElementsByClassName('child_div_1')[0].appendChild(/* ... */);
}
If the class names you've given in the example are just arbitrary, you're going to have to add some additional information to your block elements.

please add the ids for those tags that you need to refer to, it's much easier and more accurate for your javascript code to run.

Related

How to retrieve an attr value from an nextAll() retrieved list from one element?

Here's the deal: I need to look up for an element, on a list of others HTMLElements, for the next one that has the class '.wanted-class'. I fire/capture a click event in one of the elements from the same class. I ended up with a solutions that looks like this:
$('#id-element-0000').nextAll('.wanted-class');
This should return a list of all the elements that belongs to this class that are after the one I clicked. Something like this:
<div class=​"wanted-class" id=​"id-element-1111" data-wanted=​"6127">​…​</div>
<div class=​"wanted-class" id=​"id-element-2222" data-wanted=​"6128">​…​</div>
<div class=​"wanted-class" id=​"id-element-3333" data-wanted=​"6129">​…​</div>
<div class=​"wanted-class" id=​"id-element-4444" data-wanted=​"6130">​…​</div>​
But, I only want the first one. I don't need the others. So I came up (AKA: found on google) a solution that was simply:
$('#id-element-0000').nextAll('.wanted-class')[0];
This obviously return this:
<div class=​"wanted-class" id=​"id-element-1111" data-wanted=​"6127">​…​</div>
That solves the first element problem. But, I can't access the data-wanted attribute on the element. Something like:
$('#id-element-0000').nextAll('.wanted-class')[0].attr('data-wanted');
...or...
$('#id-element-0000').nextAll('.wanted-class')[0].data('wanted');
...simply don't work. And I don't seem to be able to put it into a variable too.
QUESTION: does anyone know how to retrieve the data-wanted attribute from the first element from this list?
UPDATE
Obviously, the better way of doing it was to use next intead of nextAll, BUT I have others elements between elements from this same class. So, next function doesn't apply in this case. And, YES... I've tried.
Wrap it with $() to convert it to jQuery object:
$($('#id-element-0000').nextAll('.wanted-class')[0]).attr('data-wanted');
Or simply use
$('#id-element-0000').nextAll('.wanted-class').first().attr('data-wanted');
When you index over jQuery objects, you will get HTMLElement which doesn't have methods that jQuery has.
You are accessing the first element in the jQuery wrapper set. You should convert it to jQuery object again, or get the first item with .eq method which return jQuery object:
$('#id-element-0000').nextAll('.wanted-class').eq(0).attr('data-wanted');
jsFiddle Demo.

How to getElementByID in a specific DIV block (JS or JQUery)

I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..
Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.
so instead of just
document.getElementById(target_id);
i need something like:
divName.getElementById(target_id);
or
$("document.divName").getElementById(target_id);
or
$(".divName").document.getElementById(target_id);
Can't seem to find something that works.
IDs are supposed to be unique and no two elements in page should have same id. You may search some element with some class in div with specific ID.
$('#divId .someClass')
or using find()
$('#divId').find('.someClass')
or using context, jQuery( selector [, context ] )
$('.someClass', $('#divId'))
var mySubDiv = myParentDiv.querySelector("#mySubDivId")
is equivalent to
var mySubDiv = document.querySelector("#myParentDivId #mySubDivId");
// don't forget the space : #myParentDiv#mySubDivId won't work
where querySelector and querySelectorAll are very useful functions, enough for me to avoid using jQuery : they accept any css selector
in real life, using the same Id for different DOM elements often happens.
id's should be unique, you can check for element using:
$(".your_parent_div").find("div#some_unique_id");
you can use it for the getElementsByTagName or ClassName, but ID is unique over document. so doesn't need to do that. better to use a special ID.
and in every id define as a element in javascript and you can just write id's name and use it, like this :
ID.style.color = red;
According to my understanding on your question, You have used two id's with same name when u execute, It takes only first ID so you are asking to take id from the specific div, well that is bad type of coding to use two id for same name instead go for class if want to use same name.
solution for your question is -this ->
var someDiv = document.getElementsByClassName("divName");
var someId = someDiv[0].getElementById("target_id");

How to set jQuery mouseleave function for multiple divs with same id

I have a site that has multiple divs with the same id name. I want to set a mouseleave function for all of the divs that have this id. In my $(document).ready function I have this code...
$('#my_post_container').mouseleave(function(e)
{
hideSnippet();
});
My hideSnippet() function is correct, but doing this only set the mouseleave function for the first time that a div comes up of id my_post_container. Is there a way to set the mouseleave function to all divs with this id?
I have a site that has multiple divs with the same id name.
Then you need to fix that. You must not have more than one element with the same id. id values must be unique on the page.
You probably want to use class instead, at which point your code is basically fine:
$('.my_post_container').mouseleave(function(e)
{
hideSnippet();
});
...although it coudl be shortened a bit if hideSnippet doesn't care what arguments it gets, doesn't care about this, and doesn't return false:
$('.my_post_container').mouseleave(hideSnippet);
It is invalid HTML to have multiple objects with the same id. As such, you cannot use normal selectors to find them all and you should fix your HTML to not do that.
The #1 suggestion is to fix the HTML so it does not have multiple objects with the same ID. Use a class name and you can then select them all with getElementsByClassName() or querySelectorAll() or with jQuery selectors as in:
$('.my_post_container')
If you insist on having multiple objects with the same id (a bad choice), then you will have to somewhat manually iterate over all possible objects that could have that id.
$("div[id='my_post_container']");
But, this is pretty darn inefficient because the browser can't use any of the built-in selector engine logic and it could break in the future if jQuery decides to optimize this. You really ought to switch to using class names.
You can not have multiple elements on the same page with the same id. Use a class instead, as shown here:
HTML:
<div class="my_post_container">...</div>
<div class="my_post_container">...</div>
<div class="my_post_container">...</div>
jQuery:
$('.my_post_container').mouseleave(function(e)
{
hideSnippet();
});
First of all there should not be any div elements with same ID name.. first we should solve that by keeping class name same.
then on mouse leave and enter part..
$(".testClass").on({
mouseenter : function() {
$(this).css({"background-color" : "blue"});
},
mouseleave : function() {
$(this).css({"background-color" : "green"});
}
});
this should work.. will add a js sample http://jsfiddle.net/meVc6/
and the same thing can be achived using css too..
just add css .testClass:hover { background-color:blue}

How to get element from template by javascript?

I dont know good method how to get DOM element from template by javascript.
Example template:
<script id = "template" type="text/template">
<div>text1</div>
<div>text2</div>
<div>text3</div>
</script>
For example i want get div with "text2"
There is ways which i know, all of them are bad:
Add "class" to all elements - it breaks semantics (class created for CSS). In big projects you must use very long names for classes, its very inconvenient.
Get element by his number (index) - when adding a new element, you must rewrite old numbers in your code.
I see a couple of options:
If you don't want to use class , you can use a data-* attribute.
Assuming you load the template once and then duplicate its contents as desired, you could put id values on the elements in the template, which you then remove when cloning them and adding them to the document (so you don't end up with the same id on more than one copy of the element, which would be invalid and probably counterproductive).
Maybe you can also create as many templates as you need.
One for each div.
If you need to get each div at a time you must set ids to them ... of course you can also browse the dom inside script element to find the one you're interested in ...
Home this helps
Regards
mimiz

What if I don't declare an ID in <div>?

How can I access any <div> if I don't declare the id attribute. Does DOM create ID itself?
e.g.
<div class="common_class" onmouseover="know_your_div(this)">
</div>
<script type="text/script">
function know_your_div(obj){
/*
Here i want to access the div object not by class because of it's common
for all div
*/
}
</script>
Well, the answer to your question is right there in your code.
The obj parameter that your know_your_div function takes is supplied as this in the onmouseover attribute. Thus, that is your div.
There's not an easy way to get to it in all browsers. Your best bet is to just create an ID on it. Is there a reason you can't?
Short of that, you have to navigate to it using DOM traversal methods, which are horribly unstable if your DOM structure changes at all. Code like:
document.body.childNodes[3].childNodes[2].childNodes[4];
or
document.getElementsByTagName('DIV')[22]; // 23rd DIV in the page
etc...
The answer is in your Question, let me try to help you
<div class="common_class" onmouseover="know_your_div(this)"> </div>
var oldObject = "";
function know_your_div(obj) {
// write ur condition if/ese/while/..
obj.parentNode.do_Something(); OR obj.parentNode.ID/Class/value
oldObject = obj;
}
then I guess you need to specify the ID explicitly alongside the class name..DOM won't create the ID itself...
Then it's time to use the DOM. Maybe you could use things like firstChild, lastChild, nextSibling.. http://de.selfhtml.org/javascript/objekte/node.htm
If you're using a JS library, like MooTools or jQuery, which I reccomend, you'll have a lot of powerful selector magic at your hands (example http://mootools.net/demos/?demo=Slick.Finder).
Why not use JQuery and selectors?
http://api.jquery.com/id-selector/
No, the DOM does not create an ID. You need to add an ID. You can use jQuery to access a div by it's class.

Categories