I have a class as
<div class="group-left article_left">
I need to add a id for this class dynamically using JavaScript.
i have added the following code
var thediv = document.getElementByClass("#group-left");
thediv.id = "pad_id";
But the id is not appearing in my code.Can anyone help me.
The method is called getElementsByClassName and returns a NodeList, not a single node (so you need to treat it as an array and either loop over it or just grab the first element from it).
You also need to spell your class name correctly. You don't have a # character in it.
var thediv = document.getElementsByClassName("group-left")[0];
thediv.id = "pad_id";
It isn't supported by Internet Explorer 8 or lower so you may wish to use a polyfill or a library (such as YUI or anything else implementing a selector engine) with equivalent functionality instead.
There is now getElementsByClass method in javascript unless you use some library. You can use jquery
$('.class').attr('id','pad_id');
You should only use one id per element though. Remember that
You have to use setAttribute, like such:
thediv.setAttribute("id", "pad_id");
Related
If I have something like this:
<span stylecode="123456789" class="punctis-social-widget"></span>
How can i get the stylecode value using javascript (not jquery). Also, is valid to use custom fields on spans?
Note: The field stylecode sometimes is not present, so the result of the function could be null.
It's not valid to use custom attributes. If you need to store any values consider using the HTML5 data attribute.
<span id="item1" data-stylecode="123456789" class="punctis-social-widget"></span>
Then use JS to fetch that:
<script>
var element = document.getElementById('item1'); // You could use class
var sDataValue = element.getAttribute('data-stylecode'); //123456789
</script>
For jQuery fetch value with:
$('item1').data('stylecode'); //123456789
Provided you can select the span element, you can simply do this:
spanElem.getAttribute('stylecode');
If the attribute doesn't exists, getAttribute() will simply either return null or a '' (seems to vary between browsers).
Selecting it would be easier if it had an id, in which case you could use document.getElementById('id'); Otherwise you can use document.getElementsByClassName('punctis-social-widget') in newer standards-compliant browsers, or use document.getElementsByTagName('span'); and loop over them and inspect their className properties.
As mentioned by Matthew, custom attributes are not valid (but usually don't cause any problems afaik), but provided you use HTML 5, turning it into a data-attribute will make it valid.
Though it is not good practice to use custom attributes like this, you can accomplish this task as such:
var apan = document.getElementsByTagName('span');
var code = span[0].getAttribute('stylecode');
console.log(code);
Use the data attributes.
I know how to catch the value of attribute :
var span = document.getElementsByTagName("span");
var stylecode = span.getAttribute("stylecode");
But I don't know about the second part of your question. Sorry.
I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}
How do I get the class name through JavaScript given no id with this span.
Like: <span class="xyz"></span>
I want to change the background color of this span.
How can I solve this? Please help me.
tympanus.net/Tutorials/CSS3PageTransitions/index3.html#contact
Something like this should work:
var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
if (spans[i].className == 'xyz') {
spans[i].style.backgroundColor = '#000';
}
}
You have the following choices:
Use document.getElementsByClassName("xyz"). This will return a NodeList (like an array) of objects that have that class name. Unfortunately, this function does not exist in older versions of IE.
Use document.getElementsByTagName("span") and then loop over those objects, testing the .className property to see which ones have the desired class.
Use document.querySelectorAll(".xyz") to fetch the desired objects with that class name. Unfortunately this function does not exist in older browsers.
Get a library that automatically handles all CSS3 selector queries in all browsers. If you want just a selector library, then you can use Sizzle. If you want a more comprehensive library for manipulating the DOM, then use YUI3 or jQuery (both of which have Sizzle built-in).
As of 2011, my advice is option #4. Unless this is a very small project, your development productivity will improve immensely by using a CSS3 selector library that has already been developed for cross-browser use. For example in Sizzle, you can get an array of objects with your class name with this line of code:
var list = Sizzle(".xyz");
In jQuery, you can create a jQuery object that contains a list of objects with that class with this line of code:
var list = $(".xyz");
And, both of these will work in all browsers since IE6 without you having to worry about any browser compatibility.
In more modern times (like 2021), you can use built in document.querySelectorAll() and see fairly rich CSS3 selector support.
You can use document.getElementsByClassName('xyz'). Note: it returns an array a NodeList (thanks to #IAbstractDownvoteFactory) since there can be multiple elements with the same class.
var spans = document.getElementByClassName('xyz');
var i;
for(i=0; i<spans.length; i++) {
spans[i].style.backgroundColor = your_color;
}
You can use a jquery to solve the same issue.
var classname = $(this).attr('class'); //here you will get current class name if its with multiple class split it and take first class.
$("."+classname.split(" ")[0]).css("background-color", "yellow");
I got a div, and there i got some childnodes in undefined levels.
Now I have to change the ID of every element into one div. How to realize?
I thought, because they have upgoing IDs, so if the parent is id='path_test_maindiv' then the next downer would be 'path_test_maindiv_child', and therefore I thought, I'd solve that by wildcards, for example:
document.getElementById('path_test_*')
Is this possible? Or are there any other ways?
Not in native JavaScript. You have various options:
1) Put a class and use getElementsByClassName but it doesn't work in every browser.
2) Make your own function. Something like:
function getElementsStartsWithId( id ) {
var children = document.body.getElementsByTagName('*');
var elements = [], child;
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (child.id.substr(0, id.length) == id)
elements.push(child);
}
return elements;
}
3) Use a library or a CSS selector. Like jQuery ;)
In one of the comments you say:
(...) IE is anyway banned on my page, because he doesn't get it with CSS. It's an admin tool for developer, so only a few people, and they will anyway use FF
I think you should follow a different approach from the beginning, but for what it's worth, in the newer browsers (ok, FF3.5), you can use document.querySelectorAll() with which you can get similar results like jQuery:
var elements = document.querySelectorAll('[id^=foo]');
// selects elements which IDs start with foo
Update: querySelectorAll() is only not supported in IE < 8 and FF 3.0.
jQuery allows you to find elements where a particular attribute starts with a specific value
In jQuery you would use
$('[id^="path_test_"]')
Try this in 2019 as a wildcard.
document.querySelectorAll("[id*=path_test_]")
I don't think so wildcards are allowed in getelementById.
Instead you can have all the child nodes of your respective DIV using:
var childNodeArray = document.getElementById('DIVID').childNodes;
This'll give you an array of all elements inside your DIV. Now using for loop you can traverse through all the child elements and simultaneously you can check the type of element or ID or NAME, if matched then change it as you want.
You should not change ID of element to ID of other existing element. It's very wrong, so you better re-think your core logic before going on.
What are you trying to do exactly?
Anyway, to get all elements with ID starting with something, use jQuery as suggested before, if you can't it's also possible using pure JavaScript, let us know.
I'm trying to find a way that will add / update attribute using JavaScript. I know I can do it with setAttribute() function but that doesn't work in IE.
You can read here about the behaviour of attributes in many different browsers, including IE.
element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value' might work.
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
But there are contingencies, of course.
Will not work in IE prior to 8:e.attributes['style']
Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.
Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.