简体   繁体   中英

Add a class to an element with javascript

I was wondering if someone could help me. I'm trying to add .fancy-btn to the below using JavaScript.

<div class="button transparent_2">
<a class="extra-color-3" href="#">Get a quote</a>
</div>

I want .fancy-btn class added to the div container, but cant seem to figure out how to achieve is

Thanks

您需要使用.addClass()

$(".transparent_2").addClass('fancy-btn')

Here is a JavaScript only method:

var $a = document.getElementsByClassName("transparent_2");
//assuming there is only 1 element (or is the first)
$a[0].className += " fancy-btn";

JSFiddle

see here: https://stackoverflow.com/a/507157/3503886

Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className = d.className + " otherclass";

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