user7768436
user7768436

Reputation: 35

getAttribute() not working for class name?

I am working on a touchscreen project, and try to show a few images(split one line into a few paragraphs, and use background of each paragraph to display the image), and add border for selected image (only one could be selected), now I need to display shifted images by onclick(), for example, at first it shows image 1-6, after clicking, it should display images 2-7, the problem is my border belongs to each paragraph and does not move with images, I am trying to check whether the image is selected before I slide move the image.

I could set background image for paragraph with setattribute(), assume one paragraph has the id "img5", another paragraph has id "img6":
document.getElementById('img5').setAttribute("class", "noborder"); document.getElementById('img6').setAttribute("class", "borderstyle1"); then when I try to get the attribute: var x= document.getElementById('img1').getAttribute('class'); if(x.equals("borderStyle1")) {.....} but the above is stuck and it reminds me : Uncaught TypeError: x.equals is not a function, any suggestions? thanks

Upvotes: 0

Views: 1534

Answers (2)

Joshua Robinson
Joshua Robinson

Reputation: 3563

Think you mean:

if (x === 'borderStyle1') {}

x value is a string after you call the .getAttribute method on the DOM element.

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can change to x == "borderStyle1" for comparing text string

if(x.equals("borderStyle1")){
}

to

var x= document.getElementById('img1').getAttribute('class');
 if(x == "test1"){
 alert('ok');
 }
<img src="" id="img1" class="test1" />

Upvotes: 0

Related Questions