user1365697
user1365697

Reputation: 5989

How to find element without use ID

I have DOM element in array

this.object = 
     <div>
     <span class="color">"color1</span> 
     <span class="text">text1</span>
     </div>

     <div>
     <span class="color">"color2</span> 
     <span class="text">text2</span>
     </div>

     <div>
     <span class="color">"color3</span> 
     <span class="text">text3/span>
     </div>

     <div>
     <span class="color">"color4</span> 
     <span class="text">text4</span>
     </div>

this DOM is exist in array of DOM ( this.object )

How I update only the first span or only the second span in the array, I can't use ID from technical issue of my program.

I tried to use this.element.children[i] but then I didn't know how to find the first or second span

Upvotes: 0

Views: 267

Answers (5)

Guffa
Guffa

Reputation: 700152

You would use this.element[i] to access any element in the array, and then you can access the children of those elements:

this.element[0].childNodes[0].innerHTML = "paint one";

Upvotes: 2

Paul Fleming
Paul Fleming

Reputation: 24526

Use jQuery to avoid any cross browser issues. Assuming you have the div, use div.find('span:eq(1)');

Working example.

Working example for multiple items.

Another example showing the text being updated.

Upvotes: 1

Amberlamps
Amberlamps

Reputation: 40448

You could use getElementsByClassName().

document.getElementsByClassName("color")[0];

But you have to remember two things: 1.) getElementsByClassName() is not fully cross-browser compatible. 2.) You have two know at what position your color element is. If you only using the class color once the example works perfectly.

Two solve issue 1.) you can use following workaround:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

Upvotes: 1

KooiInc
KooiInc

Reputation: 122888

You could use querySelectors:

//find first element with class 'color' within a div
//returns an element Node
[yourdiv].querySelector('.color');
//find all elements with class 'color' within a document
//returns a nodeList
document.querySelectorAll('.color');

Or getElementsByClassName:

//find first element with class 'color' within a div
//returns a nodeList with 1 or more elements
[yourdiv].getElementsByClassname('.color')[0];
//find all elements with class 'color' within a document
//returns a nodeList
document.getElementsByClassName('.color');

Upvotes: 1

Adrian Serafin
Adrian Serafin

Reputation: 7705

You should use jquery and then you can write it like this:

$('.color').html('updated text')

Upvotes: 1

Related Questions