简体   繁体   中英

Javascript element.click() not working with div tags

For some reason, this simple bit of code isn't ticking the checkbox:

<!DOCTYPE html>
<html>
<body>

<p>Automatically tick the box</p>

<form>
<div id='checkingTheBox'>
    <div class='someValue'>
        <input type="checkbox" name="checkingTheBox">
    </div>
</div>
</form>

<script type="text/javascript">

  document.getElementById("checkingTheBox").click();

</script>


</body>
</html>

However, when removing the div tags, it works fine. Is there any reason why this isn't working as it's shown, and any advice for getting the javascript to click the element successfully without changing HTML structure?

Edit: I tried using id instead of name inside the input tag. That didn't work either.

You cannot have two or more elements on the page with the same id . The id tag should be unique. Also you cannot use the name tag as a id tag. It is not the same. Here's the code example which works as you wanted to:

<!DOCTYPE html>
<html>
<body>

<p>Automatically tick the box</p>

<form>
<div>
    <div class='someValue'>
        <input type="checkbox" id="checkingTheBox">
    </div>
</div>
</form>

<script type="text/javascript">

  document.getElementById("checkingTheBox").click();

</script>


</body>
</html>

EDIT: It works but it doesn't make any sense to do that. You can just use a simple checked tag in your checkbox to have it to be checked by default. Here's an example:

<input type="checkbox" id="checkingTheBox" checked>

you are selecting the div and want to click function on it inner child so try this script that will select the inner child from your selected this and call click function on that child

const div = document.getElementById('checkingTheBox');
div.firstElementChild.firstElementChild.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM