Object.className or object.getAttribute ("className / class")?

Between both:

Javascript

function setCss(object, css) { return (object.className = css); } function getCss(object, css) { return object.className; } 

or

 function getCss2(object) { if (object.getAttribute("className")) { return object.getAttribute("className"); } return object.getAttribute("class"); } function setCss2(object, cssclass) { if (object.getAttribute("className")) { return object.setAttribute("className",cssclass); } object.setAttribute("class",cssclass); } 

HTML

 <a href="#" onClick="setCss(this, 'newclass')" /> <a href="#" class="something" onClick="alert(getCss(this))" /> <a href="#" onClick="setCss2(this, 'newclass')" /> <a href="#" class="something" onClick="alert(getCss2(this))" /> 

Both versions work in IE8, FF4, Chrome, Opera and Safari. ( jsFiddle (enhanced) demo )

Which of the best use practices and why? Have you ever encountered any problem with any version?

+6
source share
3 answers

getAttribute("class") is more universal because it can be used in different types of documents. In XML documents, most importantly. Including SVG.

element.className only works in HTML. It is described in the DOM level 2 HTML specification .

+5
source

object.getAttribute("className"); not really working.

The difference is that getAttribute gets the value of the HTML attribute since it is written in HTML code (with some exceptions).

These values โ€‹โ€‹are basically also the initial values โ€‹โ€‹of the properties of the DOM element. But access to them can give different values โ€‹โ€‹due to pre / postprocessing.

For example, if you have a <a> element, el.href gives you the full (absolute) URL, and el.getAttribute('href') gives you the URL as it was written in HTML.

In most cases, you want to access the properties of the DOM element, since they reflect the current state of the element.

+7
source

Use the first one.

Sorts. It works in every browser even with very old ones that do not support getAttribute. This is probably faster too.

But please do not use the function for this. Just use this.className and this.className = 'newClass'. Using a function for this is redundant.

+1
source

Source: https://habr.com/ru/post/891975/


All Articles