Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - get parentNode of clicked element in plain JS

I need to get the parentNode of a clicked element in plain JS (no jQuery or other frameworks) I am currently using document.getElementById("item_click") but I want to change id="item_click" to class="item_click" so I can use multiple boxes. I just don't know how to integrate this in the script

Here's a Fiddle <<< play with it

HTML

<div class="item">
    <div  class="item-tester" >
        <div class="item-icon"></div>
        <div class="item-title">Item Title</div>
    </div>
    <div id="item_click" onmousedown="new_class(event)" onmouseup="revert_class(event)" onmouseout="revert_class(event)"></div>
</div>

JS

function new_class(event) {
    wClick = document.getElementById("item_click");
    wTile = wClick.parentNode;
    wTile.className = wTile.className + " added-class";
}
function revert_class(event) {
    wTile.className = "item";
}
?

I want to change

wClick = document.getElementById("item_click");
wTile = wClick.parentNode;

to something like

wClick = this;
wTile = wClick.parentNode;

I know how to do this in jQuery but it will not work in plain JS as this would be the window (I think)

BTW. I need the (event) since this is just a stripdown of the entire code I'm using.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function new_class(event) {
    wTile = event.target.parentNode;
    wTile.className = wTile.className + " added-class";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...