Pawel
Pawel

Reputation: 191

How to click on an <li> element with javascript?

Assuming that we have html like the one below, I want to be able to click on the element using javascript just as if I it was a link.

<li class="myClass" data-type="onClick" data-target="something://url">
    <img src="img.png" alt="image"/>
    <h2> Text</h2>
</li>

Thanks

Upvotes: 0

Views: 297

Answers (2)

StrongLucky
StrongLucky

Reputation: 588

You could also use jQuery. It's more easy to work with jQuery. There you would give the li element an id or a class and then you could use this code:

$(".myClass").click( function() {
 // .. do the code
});

or with id:

$("#myID").click( function() {
 // .. do the code
});

I would also advise to put a pointer on the element by adding " cursor: pointer; " to the css. So everyone knows it's possible to click on it :)

Upvotes: 0

Nathan Q
Nathan Q

Reputation: 1902

<li class="myClass" onclick="doSomething()">
    <img src="img.png" alt="image"/>
    <h2> Text</h2>
</li>

In your javascript create the function doSomething()

And maybe use CSS on the li element:

li.myClass {
    cursor:pointer;
}

Upvotes: 2

Related Questions