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

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.

Related

How to access light DOM info from Javascript in Polymer

Question:
In Web Components specification, when you want to read elements within a Light-DOM from the template the <content select></content> element can be used. But, how can this information be retrieved from the javascript code of the component?
Example:
<wc-timer>
<wc-timer-title>I want to read this from JS</wc-timer-title>
</wc-timer>
Thanks in advance, Javier.
Remember that this inside of your prototype methods refers to the element itself. IOW, just like you could do element.innerHTML or element.firstChild you can write this.innerHTML or this.firstChild.
Simple mode:
domReady: function() {
console.log(this.textContent);
}
http://jsbin.com/bociz/2/edit
This gets more complicated if you are using <content> to project nodes through multiple levels of Shadow DOM. In this case, you will need to use getDistributedNodes api of the <content> node itself.
Before getting into that, I suggest you start with the simple version, and ask a follow up question if you get into trouble.
Use this, for accessing lightDOM and
use this.shadowRoot to access shadowDOM
I have no idea what the template renders out as to the dom, but maybe you can try this:
//jQuery
$('wc-timer-title').text();
//Plain
document.getElementsByTagName("wc-timer-title")[0].innerHTML;
You should be able to use /deep/, it is being deprecated but there is no date as to when that will happen.

How to define element without ID?

I have an element in CSS. I'm using:
ul.bjqs-controls.v-centered {to add style to it}
But in JS I need to define it and I don't have and Id, the only way to define is ul.bjqs-controls.v-centered.
I'm new in JS.
Should I use getElementById? Or what?
EDIT:
I'm trying to use jquery, but it's first time I use it, I'm trying to change element's (ul.bjqs-controls.v-centered) width to window width on page resize, but it doesn't seem to work :/
$(window).resize(function() {
$("ul.bjqs-controls.v-centered").width()=$(window).width();
});
getElementsByClassName("classname") will return a nodeList. You can loop in it and reach item what you want.
Please have a look at http://api.jquery.com/category/traversing/tree-traversal/
You can find the element by using other identified elements or using classes as people mentioned above.
you can use jquery like below
$(".ul.bjqs-controls.v-centered").html()
like that

How can I set the class for an element using jQuery? Don't want to add/remove classes

I need to set the class for an element in my page. With plain JavaScript, I would write something like:
document.getElementById('foo').className = "my_class";
This just sets the class, which is exactly what I want. But I'm using jQuery on my page and so would like to do this in a "jQuery way", since it seems weird to mix the old style and the jQuery style. But jQuery apparently only allows you use addClass() or removeClass(), like so:
$('#foo').addClass("my_class");
The problem is that it merely adds a class to the element, it does not replace the currently existing class. Does this mean I have to keep track of the old class and do a removeClass() first? Is there no way to tell jQuery to replace the current class no matter what it is and just replace it with a new one?
To remove all classes from an element:
$('#foo').removeClass();
Specifying no arguments to removeClass removes all the classes. So your solution would be:
$('#foo').removeClass().addClass('my_class');
Set the class attribute directly using .attr():
$('#foo').attr('class', 'my_class');
You could use the .attr() function like so:
$('#foo').attr('class', 'my_class');
You could use that:
$('#foo').attr('class', 'my_class');
It will replace any class with "my_class"
$('#foo').removeClass().addClass('my_class');
Ah, found the answer just seconds after I posted the question. Apparently my Google skills were insufficient... :-(
At any rate, the answer is in the removeClass() function. So, you can do:
$('#foo').removeClass().addClass("my_class");
Couldn't be simpler.
you can try using .toggleClass()

javascript : add some content in parentNode

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.

browsing through nodes

this is what an html structure of the webpage looks like:
<body>
<form>
<input type='file'/>
</form>
<div id='list'>
<div>value here<input id='delete' type='button'/></div>
</div>
</body>
i have found javascript code that triggers on 'delete' button click and removes input 'file' element. it uses this piece of code where element is input 'file' mentioned above:
deleteButton.onclick=function(){this.parentNode.element.parentNode.removeChild(
this.parentNode.element );}
i am trying to understand logic(rules) behind 'this.parentNode.element' ? why not accessing element directly 'element.parentNode.remove...'
many thanks
i am trying to understand logic(rules) behind 'this.parentNode.element' ?
There's no element property on the Node, Element, HTMLElement, or HTMLDivElement interfaces. So my guess would be that elsewhere in that code, you'll find something that's explicitly adding that property to the element instance of the div containing the button. You can do that, add arbitrary properties to element instances. These are frequently called "expando" properties and should be done very, very, very carefully.
Not the answer to the question, just opinion. It's better avoid constructions like
this.parentNode.element.parentNode
Because in case when you change your DOM structure, you will need rewrite you JS. So I think it's better to give id attributes to tags, and use next construction to get DOM element:
document.getElementById('element_id')
or if you will use some js framework (like jQuery) you can use even easier construction to get DOM element
$("#ement_id")
Ok, "removeChild" is a strange method, and quite probably, ill-conceived. It should look like:
<div>value here<input id='deleteMe' type='button'/></div>
var node = document.getElementById('deleteMe');
node.remove(); // <--- does not exist, but sure would be nice!!!
No, instead we have to do these shenanigans:
var node = document.getElementById('deleteMe');
node.parentNode.removeChild(node); // verbose! Convoluted!
We have to get the node's parent, call the method, then refer to the node again. This doesn't look like any other DOM methods as far as I recall. The good news is you can make it happen all in one line, chained, like a jQuery method.
You are best served to start over or copy somebody else's code. The use of "this" means it was within an object (or class), referring to other methods or properties within that object. You should stick to non-object variables and functions for now.
Hope that helps.

Categories