/    Sign up×
Community /Pin to ProfileBookmark

broblem with GetElementByClass

SLM;
Hi
How to get an element by its class? (note [B]an[/B] element)
I have this JS code:

[CODE]
function getElementsByClassName(className,tag){
var elements=document.getElementsByTagName(tag);
var returnElements=[];
for(i in elements)
{if(elements[i].className==className){
returnElements.push(elements[i])}
}
return returnElements}

function getClassbyNum(tTag,tClass,Num){
divs=getElementsByClassName(tClass,tTag);
var Ndiv=[];
for(x in divs)
{if(x==Num){
Ndiv.push(divs[x])
}
}
return Ndiv;}

function TryIt(){
var Obbj= getClassbyNum(‘p’,’azert’,3);
alert(Obj.InnerHTML);
}
[/CODE]

with HTML:

[CODE]
<button type=”button” onclick=”TryIt()”>getdiv by class</button>
<div class=”azert”>1</div>
<div class=”azert”>2</div>
<div class=”azert”>3</div>
<div class=”azert”>4</div>
<div class=”azert”>5</div>
[/CODE]

I should get as resault afert messege with “3”
but I get one with “undefined”
where could be the mistake ?
thnx for responding

to post a comment
JavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@KorOct 11.2011 — A lot of typos. The method is [B][COLOR="Blue"]i[/COLOR]nnerHTML[/B]. And you have referred your object as Ob[COLOR="Blue"]b[/COLOR]j, not as Obj. Moreover, you can not expect the result to be 3, but 4, because the index 3 refers the [I]4th[/I] element of the collection (as the index starts always from 0)

On the other hand all the modern browsers (except for IE7 and IE8) [I]have already implemented a native method[/I]: [B]document.getElementsByClassName()[/B]. For IE7 and IE8 you may use a workaround:
<i>
</i>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Untitled Document&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
&lt;meta http-equiv="Content-Style-Type" content="text/css"&gt;
&lt;meta http-equiv="Content-Script-Type" content="text/javascript"&gt;
&lt;script type="text/javascript"&gt;
function setClassMethod(){
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\s)" + cn+ "(?:$|\s)");
var allT = document.getElementsByTagName("*"), allCN = [], ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac &amp;&amp; ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
}
function TryIt(){
var Obbj= document.getElementsByClassName('azert')[3];
alert(Obbj.innerHTML);
}
onload=function(){
setClassMethod()
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=""&gt;
&lt;button type="button" onclick="TryIt()"&gt;getdiv by class&lt;/button&gt;
&lt;/form&gt;
&lt;div class="azert"&gt;1&lt;/div&gt;
&lt;div class="azert"&gt;2&lt;/div&gt;
&lt;div class="azert"&gt;3&lt;/div&gt;
&lt;div class="azert"&gt;4&lt;/div&gt;
&lt;div class="azert"&gt;5&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
Copy linkTweet thisAlerts:
@pactor21Oct 11.2011 — jQuery really comes in handy in this kind of situations.

All that you wanted to do can be done with this one line in jQuery.

[CODE]
<script>
var message = $("div.azert:nth-child(3)").val()");
alert(message);
</script>
[/CODE]


Well two liner. ? You can omit div from div.azert, but it is my way of coding.

By the way, the nth-child() selector is the only one whose indexing number starts from 1.
Copy linkTweet thisAlerts:
@KorOct 11.2011 — jQuery really comes in handy in this kind of situations.

All that you wanted to do can be done with this one line in jQuery.
[/QUOTE]

Illusion. In fact you should first load the JQuery's core external JS file, which weights hundreds and hundreds of code lines, which you don't need in this simple case.

In the back of the JQuery core code lays exactly the type of function I have posted. JQuery is nothing but JavaScript. It is not another language. Use JQuery only for legitimate reasons, for instance intricate effects, complex movements... the sort of things which would take you too long for coding by yourself.
Copy linkTweet thisAlerts:
@pactor21Oct 11.2011 — Kor, point taken. You are right in that I missed including the core file, and every thing you said about jQuery is correct statement to the letter. But don't you think your comment is little bit offensive? or am I the only one feeling that way?
Copy linkTweet thisAlerts:
@KorOct 11.2011 —  But don't you think your comment is little bit offensive?[/QUOTE]
No, I don't. Until you show me where's the offensive part of my comment.?
Copy linkTweet thisAlerts:
@Logic_AliOct 11.2011 — This implements or replaces document.getElementsByClassName to allow an optional tag to be specified:
&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Get Specific Tag Group by Class Name&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;script type='text/javascript'&gt;

(function()
{
if( document.getElementsByTagName )
{
document.getElementsByClassName = function( cn, tag )
{
var allElems = document.getElementsByTagName( tag || '*' ),
elemGroup = [],
rx = new RegExp( '\b' + cn + '\b' );

<i> </i> for( var i = 0, elem; ( elem = allElems[ i ] ); i++ )
<i> </i> if( elem.className.match( rx ) )
<i> </i> elemGroup.push( elem );

<i> </i> return elemGroup;
<i> </i>}
}
})();

&lt;/script&gt;
&lt;div class='nuts'&gt;&lt;/div&gt;&lt;div class='some nuts'&gt;&lt;/div&gt;
&lt;span class='nuts'&gt;&lt;/span&gt;&lt;span class='kill'&gt;&lt;/span&gt;&lt;span class='eat nuts'&gt;&lt;/span&gt;&lt;span class='nuts kill'&gt;&lt;/span&gt;

&lt;script type='text/javascript'&gt;

alert( document.getElementsByClassName( 'nuts', 'div' ).length );
alert( document.getElementsByClassName( 'nuts', 'span' ).length );
alert( document.getElementsByClassName( 'nuts' ).length );

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
Copy linkTweet thisAlerts:
@the_leaderauthorOct 11.2011 — A lot of typos. The method is [B][COLOR="Blue"]i[/COLOR]nnerHTML[/B]. And you have referred your object as Ob[COLOR="Blue"]b[/COLOR]j, not as Obj. Moreover, you can not expect the result to be 3, but 4, because the index 3 refers the [I]4th[/I] element of the collection (as the index starts always from 0)

On the other hand all the modern browsers (except for IE7 and IE8) [I]have already implemented a native method[/I]: [B]document.getElementsByClassName()[/B]. For IE7 and IE8 you may use a workaround:


[/QUOTE]

thanks at lot Kor for the code It works very well

thank you pactor21 and Ali for replying
×

Success!

Help @the_leader spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...