简体   繁体   中英

How to apply css with native js when a button is clicked on the page

I want to apply a style when clicking a button on the page. The button has a data-selector attribute. This attribute is the selector where I want to apply the css.

HTML example:

<ul>
<li><button class="button" data-selector="#skip > p > a">Button 1</button></li>
<li><button class="button" data-selector="#menu > div" >Button 2</button></li>
<li><button class="button" data-selector="#social">Button 3</button></li>
</ul>

<div id=#menu>
<div id="skip">
<p><a href="/pages">Hello</a></p>
</div>

<div id=social>
<p>Example 1</p>
<p>Example 2</p>
</div>
</div>

  <script type="text/javascript">
var error = document.querySelectorAll(".button");
    for (var i=0;i<error.length;i++){
        error[i].addEventListener("click", function() {
            var selector = error[i].getAttribute('data-selector');
            selector.style.border = '2px solid red';
        }, false);
    }
</script>

Result: error[i] is undefined

I'm using js native because I can not use jQuery

PS:Sorry for my bad english

Two errors. First, you are getting the selector string but never actually the DOM element that it represents. Second, you need to use this within the function context. Working code:

 var error = document.querySelectorAll(".button");
 for (var i=0;i<error.length;i++){
    error[i].addEventListener("click", function() {
        var selector = this.getAttribute('data-selector');
        document.querySelectorAll(selector)[0].style.border = '2px solid red';
    }, false);
}

jsfiddle: https://jsfiddle.net/h5eqg4tp/

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