3

I want to set attributes to tag without jQuery.

I have to set this dynamically.

I understand in jQuery you just do $('html') but without jQuery, I tried Document.getElementById('html') but does not work.

How can I do this?

1
  • Is your problem setting an attribute or selecting the right element(s)? Please be clear about it. Commented Nov 25, 2012 at 22:26

2 Answers 2

4

In the general case, the standard DOM equivalent to jQuery('element_name'); is document.getElementsByTagName('element_name');. Note that it returns a NodeList (which is like an array) and not just an HTMLElementNode.

The HTML element, as the root element, can be accessed via document.documentElement.

Setting attribute values can be done with the setAttribute('attribute_name', 'attribute_value'); method on an HTMLElementNode. The method is buggy in older versions of Internet Explorer, so you may wish to use the equivalent DOM property instead.

For example, to replace the value of the class attribute:

document.documentElement.className = "foo bar baz";
Sign up to request clarification or add additional context in comments.

1 Comment

While document.documentElement is equivalent, document.getElementsByTagName('html')[0] would be closer to jQuery's version I think (but I haven't trawled through its selector engine to find out).
2
document.getElementsByTagName('html')[0].setAttribute('name','value');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.