Displaying a JavaScript variable multiple times on one page with classes [duplicate] - javascript

I want to know if there is a way to getElementByClassName("classname").innerHTML function or something to the equivalent of getElementById("ClassName").innerHTML.

You are missing an s in your function name. getElementsByTagName returns a collection of elements, of elements, which you need to iterate over:
var elements = document.getElementsByClassName("classname");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = 'foo';
}
IE8 and below don't support getElementsByClassName, so you'll have to find a polyfill or use querySelectorAll (IE8).

I suggest you to use JQuery, where you can use directly CSS selectors (like .yourclass) to find all elements of a given class:
$('.yourclass').doWhatYouWant();
If you prefer not to use JQuery, you can use plain Javascript:
document.getElementsByClassName('my-fancy-class')
But be careful with IE8 incompatibility issue.
As an alternative (slower but you can build more complex CSS selectors) you can use:
document.querySelector('.cssSelector')
Which will return one element responding to your CSS selector, or
document.querySelectorAll('.cssSelector')
Which will return multiple elements instead.

You can do this using jquery
$('.className').html();
http://api.jquery.com/html/

If tou use jQuery you can get it as you would in a CSS selector so:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
then...
$('.classname').each(function() {
// get html
$(this).html();
// set html
$(this).html('something');
});
Notice you have also convenient way to manage innerHTML.

Related

javascript canvas document.getElementByClassName(); [duplicate]

why when i write
document.getElementByClass('home1').setAttribute('style', 'background-image:url(img/red_menu.PNG);');
it doesn't work?
i have the element with class="home1"
with document.getElementById('home1')...
works fine
thanks
It's getElementsByClassName, not getElementByClass; details here. Note that IE does not support this function (yet).
getElementsByClassName returns a NodeList of matching elements (rather than a single element), so:
var list, index;
list = document.getElementsByClassName("home1");
for (index = 0; index < list.length; ++index) {
list[index].setAttribute(/* ... */);
}
For this sort of thing, you may want to use a library like jQuery, Prototype, Google Closure, etc., to pave over the various browser differences for you. They can save you a lot of time and trouble compared with dealing with those differences yourself.
For instance, in jQuery:
$(".home1").attr(/* ... */);
...applies that attribute (via jQuery#attr) to every element with the class "home1". Although in your particular case, you'd probably want jQuery#css instead.
If you have only one classname in your entire HTML file, then you could also use
document.getElementsByClassName('navbar-nav')[0].setAttribute('id', 'navbar-toggle');

Find elements using part of ID

I have, the div's where id looks like this_div_id_NUMBER, all div's has the different NUMBER part. How I find all div's just using this_div_id part of id ?
you can use querySelectorAll to hit partial attribs, including ID:
document.querySelectorAll("[id^='this_div_id']")
the ^ next to the equal sign indicates "starts with", you can use * instead, but it's prone to false-positives.
you also want to make sure to use quotes (or apos) around the comapare value in attrib selectors for maximum compatibility on querySelectorAll; in jQuery and evergreen browsers it doesn't matter, but in vanilla for old browsers it does matter.
EDIT: late breaking requirement needs a more specific selector:
document.querySelectorAll("[id^='this_div_id']:not([id$='_test_field'])");
the not() segment prevents anything ending with "_test_field" from matching.
proof of concept / demo: http://pagedemos.com/partialmatch/
querySelectorAll
querySelectorAll takes CSS selectors and returns a HTMLNodeList (a kind of array) of all the elements matching that css selector.
The css selector ^ (starts with) can be used for your purpose. Learn more about it in this article.
For your case, it would be document.querySelectorAll("[id^='this_div_id']");
Note that querySelectorAll doesn't return a live node list. That means, any changes to the dom would not be updated live in the return value of the function.
Another method would to assign all your elements a specific class and then you can use getElementsByClassName (which is much faster than querySelector).
var divs = document.getElementsByClassName("divClass");
Try this selector:
[id^="this_div_id_"]
Pure JavaScript: (reference)
document.querySelectorAll('[id^="this_div_id_"]')
jQuery: (reference)
$('[id^="this_div_id_"]')
CSS: (reference)
[id^="this_div_id_"] {
/* do your stuff */
}
Why is this working?
With the [] in the selector, you can select attributes. Use '=' to match exactly the value or use the '^=' to check if the value starts with. Read more about this here.
Using attribute selectors:
div[id^="this_div_id"]
It is better to use classes.
But there is one solution that you need (assuming you use jQuery):
$("*[id^='this_div_id']")
Just using attribute selector like below:
$("[id^='this_div_id_']")

How can I use a Javascript variable as a DOM

This is kinda hard to word so i'm hoping you understand it:
I have an entire page in a variable. I need to be able to do getElementsByClassName on it. But how?
I've tried:
$.get( base_url, function( data ) {
var something = data.getElementsByClassName('.user_name');
});
If your URL returns HTML, data is a string. Since you're using jQuery, you can have jQuery parse it for you:
var dom = $(data);
Then you can use all the usual jQuery methods on that disconnected set of elements, so:
var userNames = dom.find(".user_name");
If you weren't using jQuery, you could have the browser parse that into elements for you:
var div = document.createElement('div');
div.innerHTML = data;
...and then use use DOM methods on that disconnected div. I wouldn't use getElementsByClassName, though; querySelectorAll has better support; basically, it's in all modern browsers and also in IE8, but IE8 doesn't have getElementsByClassName.
var userNames = div.querySelectorAll(".user_name");
You are mixing pure javascript with JQuery
Try this
data.getElementsByClassName('user_name');
instead of
data.getElementsByClassName('.user_name');

How to use JavaScript's setattribute to affect multiple elements?

I have many div with the class publish_0 that I would like to change to publish_1 on click of a button.
Right now I use this but it only change one item.
How to I apply the setattribute to all item that have the publish_0.
document.querySelector('.publish_0').setAttribute("class", "publish_1");
You need to use a loop to iterate over all the elements and set their class attribute value individually:
var els = document.querySelectorAll('.publish_0');
for (var i=0; i < els.length; i++) {
els[i].setAttribute("class", "publish_1");
}
For when you can't use jQuery but want the convenience of something similar, you can do the following. Add the following code to the top of the file or somewhere else easily visible.
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
Now in your code you can do this:
document.querySelectorAll('body,main,article,[class*=content],[class*=center]')
.forEach((function(x){ x.setAttribute("style","width:1920px");}))
Or even nicer yet, if the browser supports ECMAScript2015 you can use arrow syntax:
document.querySelectorAll('[class*=content]')
.forEach( x=> x.setAttribute("style","width:1200px"))
You can put the statement all on one line if you'd like.
You can use this with jquery:
$(".publish_0").attr("class", "publish_1")
Alternatively, use getElementsByClassName and loop through the DOM elements returned.

getElementByClass().setAttribute doesn't work

why when i write
document.getElementByClass('home1').setAttribute('style', 'background-image:url(img/red_menu.PNG);');
it doesn't work?
i have the element with class="home1"
with document.getElementById('home1')...
works fine
thanks
It's getElementsByClassName, not getElementByClass; details here. Note that IE does not support this function (yet).
getElementsByClassName returns a NodeList of matching elements (rather than a single element), so:
var list, index;
list = document.getElementsByClassName("home1");
for (index = 0; index < list.length; ++index) {
list[index].setAttribute(/* ... */);
}
For this sort of thing, you may want to use a library like jQuery, Prototype, Google Closure, etc., to pave over the various browser differences for you. They can save you a lot of time and trouble compared with dealing with those differences yourself.
For instance, in jQuery:
$(".home1").attr(/* ... */);
...applies that attribute (via jQuery#attr) to every element with the class "home1". Although in your particular case, you'd probably want jQuery#css instead.
If you have only one classname in your entire HTML file, then you could also use
document.getElementsByClassName('navbar-nav')[0].setAttribute('id', 'navbar-toggle');

Categories